The Right Way to writing Models
- liko28s
- Member | 6
Hi Guys, i'm writting a MVC application, and i'm trying to use Models in the structure
I have this as Model:
EquipmentModel.php
<?php
namespace App\HealthnoteModule\Models;
use Nette, Nette\Database\Context;
class EquipmentModel extends Nette\Object {
/** @var Nette\Database\Connection */
public $database;
private $tableName = "equipment";
public function __construct(Nette\Database\Connection $database) {
$this->database = new Context($database,
new Nette\Database\Structure(
$database,
new Nette\Caching\Storages\MemoryStorage
)
);
}
}
And i like to use in my presenter as follows:
namespace App\HealthnoteModule\Presenters;
use Nette, App\HealthnoteModule\Models;
class MonitoringPresenter extends Nette\Application\UI\Presenter {
/** @var Models\EquipmentModel @inject */
private $equipmentModel;
public function __construct(Models\EquipmentModel $equipmentModel) {
$this->equipmentModel = $equipmentModel;
}
public function renderDefault() {
$this->template->equipments = $this->equipmentModel->fetchAll();
}
//.... a lot of code
public function handleEquipment($time, $state) {
$this->equipmentModel->insert(array($this->serviceOrder, $time, $state));
}
}
But EquipmentModel class extends from Nette\Object, that does not include the methods get (), fetch (), fetchAll () … any ideas?
Thanks
- Armin Schmidtke
- Member | 20
Hi @liko28s,
no the methods are not included. You have to define them in your models. For
example:
<?php
/** @return Nette\Database\Table\Selection */
public function fetchAll()
{
return $this->database->table('tablename');
}
?>
Have a look at this example App, its a great and easy starting point:
https://github.com/…D-collection
- Armin Schmidtke
- Member | 20
To complete your code…
EquipmentModel.php:
<?php
namespace App\HealthnoteModule\Models;
use Nette,
Nette\Database\Context;
class EquipmentModel extends Nette\Object
{
/** @var Nette\Database\Context */
private $database;
public function __construct(Nette\Database\Context $database)
{
$this->database = $database;
}
/** @return Nette\Database\Table\Selection */
public function fetchAll()
{
return $this->database->table('equipment');
}
}
?>
config.neon:
services:
- App\HealthnoteModule\Models\EquipmentModel
then it should work in your presenter.
Last edited by Armin Schmidtke (2016-06-15 23:03)
- pata.kusik111
- Member | 78
I would also suggest to write an abstract class with all the usual CRUD methods and then for the models to extend from this class. An example from one of my older projects.