Andreas S
Andreas S

Reputation: 461

ZF2 + Doctrine 2 & access to zf config

I have a doctrine entity that holds a reference to a file. When the entity is deleted, the referenced file should also be removed using @HasLifecycleCallbacks and preRemove(). The problem is, that the reference to the file saved in the entity is a relative path and the first part to complete it, is saved in the zf2 config.

How can I access the zf2 config from within the entity, so that I can build a complete path and delete the file?

Upvotes: 1

Views: 398

Answers (1)

Microbe
Microbe

Reputation: 465

It is possible to inject anything you wish into entity by attach event listener.

Your main Module.php file:

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 class:

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

All your entities must extends class with method setServiceManager. After that application config inside entity:

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

If you don't need to inject all service manager, but just config, instead of setServiceManager method make setApplicationConfig method:

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

Upvotes: 3

Related Questions