天天看点

Zend Framework2 - 在 Module.php中检查管理是否登录,而不是到控制器中检查 (实现方法示例)

 在ZF2中应使用事件驱动方法实现,  会影响所有模块?

是否只仅作用于当前模块?

>>方法一

    (This should be done with event in ZF2 for more details:

    click here(参考官方方法http://framework.zend.com/manual/2.0/en/modules/zend.event-manager.event-manager.html)

     also this code may help you. http://pastebin.com/FFGVCpki)

    public function init() {

        // Attach Event to EventManager

        $events = StaticEventManager::getInstance ();

        // Add event of authentication before dispatch

        $events->attach ( 'Zend\Mvc\Controller\AbstractActionController', 'dispatch', array (

            $this,

            'authPreDispatch'

        ), 110 );

    }

    public function authPreDispatch($event){

    $target = $event->getTarget ();

    $serviceLocator = $target->getServiceLocator();

    // Do what ever you want to check the user's identity

    $url = $event->getRouter ()->assemble ( array (

                "controller" => "<controller>"

            ), array (

                'name' => '<route name>'

            ) );

    $response = $event->getResponse ();

        $response->setHeaders ( $response->getHeaders ()->addHeaderLine ( 'Location', $url ) ));

        $response->setStatusCode ( 302 );

        $response->sendHeaders ();

        exit ();

    }

    >>方法二:

    //filename : SanAuthWithDbSaveHandler/Module.php

    namespace SanAuthWithDbSaveHandler;

    use Zend\Mvc\MvcEvent;

    class Module

    {

     public function onBootstrap(MvcEvent $e)

     {

     $em = $e->getApplication()->getEventManager();

     $em->attach('route', array($this, 'checkAuthenticated'));

     }

     public function isOpenRequest(MvcEvent $e)

     {

     if ($e->getRouteMatch()->getParam('controller') == 'SanAuthWithDbSaveHandler\Controller\AuthController') {

     return true;

     }

     return false;

     }

     public function checkAuthenticated(MvcEvent $e)

     {

     if (!$this->isOpenRequest($e)) {

     $sm = $e->getApplication()->getServiceManager();

     if (! $sm->get('AuthService')->getStorage()->getSessionManager()

     ->getSaveHandler()->read($sm->get('AuthService')->getStorage()->getSessionId())) {

     $e->getRouteMatch()

     ->setParam('controller', 'SanAuthWithDbSaveHandler\Controller\Auth')

     ->setParam('action', 'index');

     }

     }

     }

  >> ---------- 根据MVC $e获取tabelGateway -----------------

     $e->getApplication()->getServiceManager()->get('Admin\Model\ModsTable')->sideBar()

   ' Admin\Model\ModsTable' 在public function getServiceConfig() 中配置注入

    public function getConfig()

    {

        return include __DIR__ . '/config/module.config.php';

    }

  }

>>官方添加模块事件管理方法

http://framework.zend.com/manual/2.0/en/modules/zend.event-manager.event-manager.html