Proper way to create a Symfony2 helper class which is available to all bundles
symfony
Solution
Ok, for some reason the process of defining my question here helped me solve how to do this. I did create a service.
class AclHelper {
protected $aclProvider;
protected $securityContext;
protected $logger;
public function __construct(MutableAclProvider $aclProvider, $securityContext, $logger) {
$this->aclProvider = $aclProvider;
$this->securityContext = $securityContext;
$this->logger = $logger;
}
public function bindUserToObject($object, $mask) {
// creating the ACL
$objectIdentity = ObjectIdentity::fromDomainObject($object);
$acl = $aclProvider->createAcl($objectIdentity);
// retrieving the security identity of the currently logged-in user
$user = $this->securityContext->getToken()->getUser();
$securityIdentity = UserSecurityIdentity::fromAccount($user);
// grant owner access
$acl->insertObjectAce($securityIdentity, $mask);
$aclProvider->updateAcl($acl);
}
}
Then I added it to my services.yml file:
parameters:
acl_helper.class: GC\DashboardBundle\Services\AclHelper
services:
acl_helper:
class: %acl_helper.class%
arguments: [@security.acl.provider, @security.context, @logger]
Now in my controller, all I have to do is:
$this->get('acl_helper')->bindUserToObject($object, MaskBuilder::MASK_OWNER);
Problem
I'm implementing an ACL system for my models and I want to extract the common code into a common Helper class. I can't find any examples of how to properly do something like this, but I constantly find the need to do it. For example, let's say that in my controller I have a chunk of code (taken right from the docs): ``` // creating the ACL $aclProvider = $this->get('security.acl.provider'); $objectIdentity = ObjectIdentity::fromDomainObject($asset); $acl = $aclProvider->createAcl($objectIdentity); // retrieving the security identity of the currently logged-in user $securityContext = $this->get('security.context'); $user = $securityContext->getToken()->getUser(); $securityIdentity = UserSecurityIdentity::fromAccount($user); // grant owner access $acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER); $aclProvider->updateAcl($acl); ``` I would much rather have the following: ``` $this->get('my_helpers')->bindUserToObject($asset, MaskBuilder::MASK_OWNER); ``` How should I go about implementing the 'my_helpers' service? I'm pretty sure it would be a service, but I still find the concept of 'services' to be a little confusing.