2013-12-20 49 views
1

我有一个学说的实体,它持有对文件的引用。当实体被删除时,引用的文件也应该使用@HasLifecycleCallbacks和preRemove()来删除。问题是,保存在实体中的文件的引用是一个相对路径,并且完成它的第一部分保存在zf2配置中。ZF2 +学说2&访问zf配置

如何从实体内部访问zf2配置,以便我可以构建完整路径并删除文件?

回答

3

可以通过附加事件侦听器将任何想要的东西注入实体。

你的主要Module.php文件:

namespace Application 

class Module 
{ 
    public function onBootstrap (MvcEvent $e) 
    { 
     /* 
     * inject service manager into entities on postload event 
     */ 
     $serviceManager = $e->getApplication()->getServiceManager(); 
     $doctrineEventManager = $serviceManager 
      ->get('doctrine.entitymanager.orm_default') 
      ->getEventManager(); 
     $doctrineEventManager->addEventListener(
      array(\Doctrine\ORM\Events::postLoad), 
      new \Application\Entity\InjectListener($serviceManager) 
     ); 
    { 
} 

Application\Entity\InjectListener类:

namespace Application\Entity; 

class InjectListener 
{ 
    private $sm; 

    public function __construct($sm) 
    { 
     $this->sm = $sm; 
    } 

    public function postload($eventArgs) 
    { 
     $entity = $eventArgs->getEntity(); 
     $entity->setServiceManager($this->sm); 
    } 
} 

你所有的实体都必须扩展类方法setServiceManager。内部实体应用程序配置后:

$config = $this->sm->get('Configuration'); 

如果您不需要注入所有的业务经理,但仅仅配置,而不是setServiceManager方法使setApplicationConfig方法:

namespace Application\Entity; 

class InjectListener 
{ 
    private $config; 

    public function __construct($sm) 
    { 
     $this->sm = $sm; 
    } 

    public function postload($eventArgs) 
    { 
     $entity = $eventArgs->getEntity(); 
     $entity->setApplicationConfig(
      $this->sm->get('Configuration') 
     ); 
    } 
} 
+0

谢谢!伟大的解决方案... –

+0

若要更新此答案一点点,如果您不想更新所有实体,您应该创建一个接口并在需要它的实体中实现。所以像'ServiceManagerAwareInterface'这样的东西,然后你可以很容易地检查你的'InjectListener :: postLoad()'实体是否是'ServiceManagerAwareInterface'的实例,如果是的话你可以设置管理器。 – Kwido