I am trying to implement some basic ACL into my Symfony2 application, and to ensure that the users only accesses entities that they are allowed to access I have created an interface (UserAware) and a doctrine filter that appends a "entity_table.user_id=SESSION_USERID" where clause to the query.

This works perfectly, but then I realized that if I was able to set the user object of all entities being persisted with the UserAware interface then I would not have to worry about adding the user object myself other than adding the interface to the entities.

Is it possible to do this as simple as the single filter with something like a global lifecycle onflush event, or do I have to add lifecycle events to all of the entities?

有帮助吗?

解决方案

Yes, it's possible to add listeners globally.

First create a listener (this example listens to the PreUpdate event):

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;

class MyEventListener
{
    public function preUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        $entityManager = $args->getObjectManager();

        // do what you want to do...
    }
}

Then register your listener.

You can do this before the EntityManager is created:

$eventManager = new \Doctrine\Common\EventManager();
$eventManager->addEventListener(array(\Doctrine\ORM\Events::preUpdate), new MyEventListener());

$entityManager = \Doctrine\ORM\EntityManager::create($dbOpts, $config, $eventManager);

Or after it is created:

$eventManager = $entityManager->getEventManager();
$eventManager->addEventListener(array(\Doctrine\ORM\Events::preUpdate), new MyEventListener());

Read more about life-cycle events in the docs.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top