I have two controllers in my Module and both of them need to see if the user is logged in or not. The Login controllers authenticates the user using DbTable and writes the identity into the storage.
I am using >Zend\Authentication\AuthenticationService; $auth = new AuthenticationService();
inside the controller function but then i instantiate its instance on multiple pageAction()
for this i wrote a function into the Module.php
as follows
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Config\DbAdapter' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
return $dbAdapter;
},
'Admin\Model\PagesTable' => function($sm){
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$pagesTable = new PagesTable(new TableGateway('pages',$dbAdapter) );
return $pagesTable;
},
'Admin\Authentication\Service' => function($sm){
return new AuthenticationService();
}
),
);
}
As you can see i am returning new AuthenticationService() every time which i think is bad. I could not find how to grab the already instantiated instance of the service or i have to write a singleton class for this. Please advise any sample code snipets with deeper explaination would be highly regarded and appreciated thanks.
Try this instead:
public function getServiceConfig()
{
return array(
'aliases' => array(
'Application\Config\DbAdapter' => 'Zend\Db\Adapter\Adapter',
'Admin\Authentication\Service' => 'Zend\Authentication\AuthenticationService',
),
'factories' => array(
'Admin\Model\PagesTable' => function ($serviceManager) {
$dbAdapter = $serviceManager->get('Application\Config\DbAdapter');
$tableGateway = new TableGateway('pages', $dbAdapter);
$pagesTable = new PagesTable($tableGateway);
return $pagesTable;
},
),
);
}
Note mainly the 'aliases' section of the root array, any other changes are just cosmetic and you may prefer to do the original way you suggested (such as using a factory to retrieve the Zend\Db\Adapter\Adapter instance instead of aliasing that too).
Kind Regards,
ise
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With