Zend framework 2 AuthenticationService

I have two controllers in my module and they need to find out if the user is logged in or not. Login controllers authenticate the user with DbTable and write the identifier to the store.

I use> Zend \ Authentication \ AuthenticationService; $ auth = new AuthenticationService ();

inside the controller function, but then I instantiate it on multiple pages (A)

for this I wrote a function in Module.php

in the following way

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 return a new AuthenticationService () every time I think it is bad. I could not find how to capture an already created instance of the service, or I should write one class for this. Please inform that any samples of snipers with deeper explanations will be highly appreciated and appreciated.

+6
source share
1 answer

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; }, ), ); } 

Pay attention to the section "aliases" of the root array, any other changes are just cosmetic, and you may prefer to make the original method that you suggested (for example, using factory to extract Zend \ Db \ Adapter \ Adapter instead of aliasing).

Respectfully,

ISE

+2
source

All Articles