2012-09-14 16 views
7

Estoy tratando de obtener el localizador de servicios/administrador de entidades en la clase de complementos, ¿cómo puedo obtener eso?ZF2 getServiceLocator en ControllerPlugin clase

En mi controlador lo obtengo así.

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

pero en clase de complemento que estoy consiguiendo error en $ this-> getServiceLocator() de la línea. porque esto no está disponible en la clase de complemento.

¿Cómo puedo hacer lo mismo para poder recuperar algunos registros e insertar pocos en la base de datos en el complemento?

me tienen MvcEvent $ e objeto en mi clase de complemento, puedo hacer uso de esto para conseguir gestor de la entidad?

he utilizado this plugin para crear mi complemento

será appriciated Cualquier guía.

actualización:

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

} 

Estoy llamando por encima de la clase en 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...  

    } 

estoy registrando este plugin en 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', 
    ), 
    ), 
); 

Respuesta

8

¿Qué haces significa con "clase de complemento"? En caso de que hable sobre los complementos del controlador, puede acceder utilizando (desde el alcance del complemento del controlador): $this->getController()->getServiceLocator()->get('doctrine.entitymanager.orm_default');.

Para otras clases, generalmente creo una fábrica que inyecta la instancia de ServiceManager automáticamente. Por ejemplo, en la clase del módulo:

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

clase de complemento está bajo control \ Plugin \ y es invocable mediante el uso de matriz de retorno (=> array 'controller_plugins' (=> array 'invokables' ( 'AclPlugin' => 'Auth \ Controller \ Plugin \ AclPlugin', ), ),); pero de alguna manera obtengo un error cuando uso $ this-> getController() -> getServiceLocator() -> get ('doctrine.entitymanager.orm_default'); en el error de clase de complemento es un error fatal: llamar a una función miembro getServiceLocator() en un no objeto en /module/Auth/src/Auth/Controller/Plugin/AclPlugin.php – Developer

+0

¿Puedes pegar la clase de tu complemento de controlador? Hago esto exactamente de la misma manera y funciona para mí. Además, indique su versión de ZF2 (betaN/RCn/2.0.0). –

+0

versión es zf2 estable relase 2.0.0. Consulte la clase en la pregunta anterior – Developer

2

cambió la clase AclPlugin encima como por debajo de

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

En realidad, hacer ServiceManager en el plugin de control es muy fácil!

sólo tiene que utilizar: $this->getController()->getServiceLocator()

Ejemplo:

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); 
    } 
} 
Cuestiones relacionadas