2012-09-14 2 views
7

Я пытаюсь получить менеджер локатора/сущности в классе плагинов, как я могу это получить.ZF2 getServiceLocator в классе ControllerPlugin

В моем контроллере я получаю его вот так.

public function getEntityManager() 
{ 
    if(null === $this->em){ 
     $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default'); 
    } 
    return $this->em; 
} 

public function setEntityManager(EntityManager $em) 
{ 
    $this->em = $em; 
} 

но в классе плагин я получаю сообщение об ошибке на $ this-> getServiceLocator() линии. потому что это недоступно в классе плагинов.

Как я могу сделать то же самое, чтобы получить некоторые записи и вставить несколько в базу данных в плагине.

У меня есть объект MvcEvent $ e в моем классе плагинов, я могу использовать это для получения диспетчера сущностей?

Я использовал this plugin создать свой плагин

Любое руководство будет appriciated.

обновление:

namespace Auth\Controller\Plugin; 

use Zend\Mvc\Controller\Plugin\AbstractPlugin; 
use Zend\EventManager\EventInterface as Event; 
use Zend\Authentication\AuthenticationService; 

use Doctrine\ORM\EntityManager; 
use Auth\Entity\User; 
use Zend\Mvc\MvcEvent; 
class AclPlugin extends AbstractPlugin 
{ 

    /* 
    * @var Doctrine\ORM\EntityManager 
    */ 
    protected $em; 

    public function checkAcl($e) 
    { 

     $auth = new AuthenticationService(); 
     if ($auth->hasIdentity()) { 
      $storage = $auth->getStorage()->read();    
      if (!empty($storage->role)) 
       $role = strtolower ($storage->role);    
      else 
       $role = "guest";    
     } else { 
      $role = "guest";    
     } 
     $app = $e->getParam('application'); 
     $acl   = new \Auth\Acl\AclRules(); 

     $matches  = $e->getRouteMatch(); 
     $controller = $matches->getParam('controller'); 
     $action  = $matches->getParam('action', 'index'); 

     $resource = strtolower($controller); 
     $permission = strtolower($action); 

     if (!$acl->hasResource($resource)) { 
      throw new \Exception('Resource ' . $resource . ' not defined'); 
     } 

     if ($acl->isAllowed($role, $resource, $permission)) { 

      $query = $this->getEntityManager($e)->createQuery('SELECT u FROM Auth\Entity\User u'); 
      $resultIdentities = $query->execute(); 

      var_dump($resultIdentities); 
      exit(); 


      return; 

     } else { 
      $matches->setParam('controller', 'Auth\Controller\User'); // redirect 
      $matches->setParam('action', 'accessdenied');  

      return; 
     } 


    } 


    public function getEntityManager($e) { 

     var_dump($this->getController()); // returns null 
     exit(); 
     if (null === $this->em) { 
      $this->em = $this->getController()->getServiceLocator()->get('doctrine.entitymanager.orm_default'); 

     } 
     return $this->em; 
    } 

    public function setEntityManager(EntityManager $em) { 
     $this->em = $em; 
    } 

} 

Я зову выше класса в module.php

public function onBootstrap(Event $e) 
    { 

     $application = $e->getApplication();   
     $services = $application->getServiceManager();   

     $eventManager = $e->getApplication()->getEventManager(); 
     $eventManager->attach('dispatch', array($this, 'loadConfiguration'),101); 

    } 

public function loadConfiguration(MvcEvent $e) 
    { 

     $e->getApplication()->getServiceManager() 
        ->get('ControllerPluginManager')->get('AclPlugin') 
        ->checkAcl($e); //pass to the plugin...  

    } 

Я регистрации этого плагина в module.config.php

return array( 
'controllers' => array(
     'invokables' => array(
      'Auth\Controller\User' => 'Auth\Controller\UserController', 
     ), 
    ), 

    'controller_plugins' => array(
     'invokables' => array(
      'AclPlugin' => 'Auth\Controller\Plugin\AclPlugin', 
    ), 
    ), 
); 

ответ

8

Что вас означает «Plugin Class»? Если вы говорите о плагинах контроллера abount, вы можете получить к нему доступ, используя (из области плагина контроллера): $this->getController()->getServiceLocator()->get('doctrine.entitymanager.orm_default');.

Для других классов обычно я создаю фабрику, которая автоматически вводит экземпляр ServiceManager. Например, в классе модуля:

public function getServiceConfig() 
{ 
    return array(
     'factories' => array(
      'myServiceClass' => function(ServiceManager $sm) { 
       $instance = new Class(); 
       $instance->setServiceManager($sm); 
       // Do some other configuration 

       return $instance; 
      }, 
     ), 
    ); 
} 

// access it using the ServiceManager where you need it 
$myService = $sm->get('myService'); 
+0

плагин класс под контроллер \ Plugin \ и доступен посредством использования возвращаемого массива ('controller_plugins' => Array ( 'invokables' => массив ( 'AclPlugin' => 'Auth \ Controller \ Plugin \ AclPlugin', ), ),); но почему-то я получаю ошибку, когда я использую $ this-> getController() -> getServiceLocator() -> get ('doctrine.entitymanager.orm_default'); в ошибке класса плагина Fatal error: вызов функции-члена getServiceLocator() для не-объекта в /module/Auth/src/Auth/Controller/Plugin/AclPlugin.php – Developer

+0

Можете ли вы вставить свой класс плагина контроллера? Я делаю это точно так же, и это работает для меня. Также укажите свою версию ZF2 (betaN/RCn/2.0.0). –

+0

версия zf2 stable relase 2.0.0. см. класс, о котором идет речь выше – Developer

2

изменил выше класс AclPlugin ниже

namespace Auth\Controller\Plugin; 

use Zend\Mvc\Controller\Plugin\AbstractPlugin; 
use Zend\EventManager\EventInterface as Event; 
use Zend\Authentication\AuthenticationService; 

use Doctrine\ORM\EntityManager; 
use Auth\Entity\User; 
use Zend\Mvc\MvcEvent; 

use Zend\ServiceManager\ServiceManagerAwareInterface; 
use Zend\ServiceManager\ServiceManager; 
class AclPlugin extends AbstractPlugin implements ServiceManagerAwareInterface 
{ 

    /* 
    * @var Doctrine\ORM\EntityManager 
    */ 
    protected $em; 

    protected $sm; 

    public function checkAcl($e) 
    { 

     $this->setServiceManager($e->getApplication()->getServiceManager()); 

     $auth = new AuthenticationService(); 
     if ($auth->hasIdentity()) { 
      $storage = $auth->getStorage()->read();    
      if (!empty($storage->role)) 
       $role = strtolower ($storage->role);    
      else 
       $role = "guest";    
     } else { 
      $role = "guest";    
     } 
     $app = $e->getParam('application'); 
     $acl   = new \Auth\Acl\AclRules(); 

     $matches  = $e->getRouteMatch(); 
     $controller = $matches->getParam('controller'); 
     $action  = $matches->getParam('action', 'index'); 

     $resource = strtolower($controller); 
     $permission = strtolower($action); 

     if (!$acl->hasResource($resource)) { 
      throw new \Exception('Resource ' . $resource . ' not defined'); 
     } 

     if ($acl->isAllowed($role, $resource, $permission)) { 

      $query = $this->getEntityManager($e)->createQuery('SELECT u FROM Auth\Entity\User u'); 
      $resultIdentities = $query->execute(); 

      var_dump($resultIdentities); 
      foreach ($resultIdentities as $r) 
       echo $r->username; 
      exit(); 


      return; 

     } else { 
      $matches->setParam('controller', 'Auth\Controller\User'); // redirect 
      $matches->setParam('action', 'accessdenied');  

      return; 
     } 

    } 



    public function getEntityManager() { 

     if (null === $this->em) { 
      $this->em = $this->sm->getServiceLocator()->get('doctrine.entitymanager.orm_default'); 

     } 
     return $this->em; 
    } 

    public function setEntityManager(EntityManager $em) { 
     $this->em = $em; 
    } 

    /** 
    * Retrieve service manager instance 
    * 
    * @return ServiceManager 
    */ 
    public function getServiceManager() 
    { 
     return $this->sm->getServiceLocator(); 
    } 

    /** 
    * Set service manager instance 
    * 
    * @param ServiceManager $locator 
    * @return void 
    */ 
    public function setServiceManager(ServiceManager $serviceManager) 
    { 
     $this->sm = $serviceManager; 
    } 

} 
1

На самом деле получение ServiceManager в контроллер плагин очень просто!

Просто используйте: $this->getController()->getServiceLocator()

Пример:

namespace Application\Controller\Plugin; 

use Zend\Mvc\Controller\Plugin\AbstractPlugin; 

class Translate extends AbstractPlugin 
{ 

    public function __invoke($message, $textDomain = 'default', $locale = null) 
    { 
     /** @var \Zend\I18n\Translator\Translator $translator */ 
     $translator = $this->getController()->getServiceLocator()->get('translator'); 

     return $translator->translate($message, $textDomain, $locale); 
    } 
} 
Смежные вопросы