Skip to content

Instantly share code, notes, and snippets.

@lavoiesl
Created August 21, 2012 04:04
Show Gist options
  • Save lavoiesl/3411401 to your computer and use it in GitHub Desktop.
Save lavoiesl/3411401 to your computer and use it in GitHub Desktop.
Workaround for circular dependency in Symfony2 services
<?php
namespace Acme\SiteBundle\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Acme\SiteBundle\Entity\Comment;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;
use Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException;
class CommentsAcl
{
private $container;
/**
* Inject the whole container because otherwise we would have a circular dependency
* DBAL -> ORM -> EventManager -> ACL Provider
* @link https://groups.google.com/d/topic/symfony2/MreLJgfnn_U/discussion
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$aclProvider = $this->container->get('security.acl.provider');
if ($entity instanceof Comment) {
// Add operator rights to target so it can manage the comments on his person
if (($person = $entity->getTarget()) && ($user = $person->getUser())) {
$securityIdentity = UserSecurityIdentity::fromAccount($user);
$objectIdentity = ObjectIdentity::fromDomainObject($entity);
try {
$acl = $aclProvider->createAcl($objectIdentity);
} catch (AclAlreadyExistsException $e) {
$acl = $aclProvider->findAcl($objectIdentity);
}
$acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OPERATOR);
}
$aclProvider->updateAcl($acl);
}
}
}
services:
acme.listener.acl.comments:
class: Acme\SiteBundle\Listener\CommentsAcl
arguments: [ @service_container ]
tags:
- { name: doctrine.event_listener, event: postPersist }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment