Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zend framework 2 AuthenticationService

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.

like image 210
Jani Pitscutecy Avatar asked Dec 07 '12 09:12

Jani Pitscutecy


1 Answers

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

like image 198
ise Avatar answered Oct 19 '22 14:10

ise