I am developing my app in ZF2 but despite trying i could not find answer for my database/model problem.
I think of TableGateway that is pretty much the copy of skeleton application example as a AdminUser collection of some sorts that does the query tasks and returns AdminUser instance.
this is part of Module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Admin\Model\AdminUserTable' => function($sm) {
$tableGateway = $sm->get('AdminUserTableGateway');
$table = new AdminUserTable($tableGateway);
return $table;
},
'AdminUserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new AdminUser());
return new TableGateway('zxf_admin_user', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
here is the controller
protected $adminUserTable;
public function indexAction()
{
$this->layout('layout/admin');
return new ViewModel(array(
'text' => 'some text',
'users' => $this->getAdminUserTable()->fetchAll(),
));
}
public function getAdminUserTable()
{
if (!$this->adminUserTable) {
$sm = $this->getServiceLocator();
$this->adminUserTable = $sm->get('Admin\Model\AdminUserTable');
}
return $this->adminUserTable;
}
I am not sure of the getAdminUserTable approach,and this is the function that gets user
public function getAdminUser($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
but what if I am interested in having another class something like AdminUserPriviliges that would be object that is returned when you do this in your controller
$user = $this->getAdminUserTable()->getAdminUser($id);
to get privileges even though they are different class and data for them is stored in different table, hence the below method would need to perform database search but because inside AdminUser object it could use the $this->id and furthermore via AdminUser you would get access to privileges themselves so I could then get them on request as a collection of objects, something like this
$user_piviliges = $user->getPriviliges();
and the content should be collection of AdminUserPriviliges instances
return new ViewModel(array(
'text' => 'some text',
'user' => $this->getAdminUserTable()->getAdminUser($id);,
));
so sending user objects back to view would mean we have the privileges too. in a similar way when i move to other entities i would like to be able to do the same
like $product->getImages() would give you all images but they are not stored in the same table of course.
Is there a better way to do it or even simpler?