Friday, July 1, 2016

Symfony DIC: setter injection

Most of the time, when defining a service I inject into constructor parameters or other services. But it is possible to use the Symfony DIC to inject parameters/services into setter methods:

     newsletter_manager:
         class:     NewsletterManager
         calls:
             - [setMailer, ['@my_mailer']]

http://symfony.com/doc/current/components/dependency_injection/types.html
 

Where:

setMailer  - is the name of the method
['@my_mailer'] - is the name of the service being injected

Practical example with Sonata

If you are using Sonata Admin Bundle and Sonata User Bundle, you may want to access the Entity Manager for some reasons. For this we will inject the service ''@doctrine.orm.entity_manager" using a setter method.

I will create a bundle named ApplicationSonataAdminUserBundle where I will place my new Admin class. In the project's services.yml I will add the new service definition:


sonata.user.admin.user:
        class: Application\Sonata\UserBundle\Admin\Model\UserAdmin
        arguments: [~,"%sonata.user.admin.user.entity%","SonataAdminBundle:CRUD"]
        calls:
            - [setUserManager, ['@fos_user.user_manager']]
            - [setTranslationDomain, ['%sonata.user.admin.user.translation_domain%']]
             - [setEntityManager, ["@doctrine.orm.entity_manager"]]
        tags:
            - { name: sonata.admin, manager_type: orm, group: "sonata_user", label: "users", label_catalogue: "SonataUserBundle",label_translator_strategy: "sonata.admin.label.strategy.underscore",icon: "<![CDATA[<i class='fa fa-users'></i>]]>" }


And of course in the class I will add the setter method "setAuthorizationChecker":

use Sonata\AdminBundle\Admin\AbstractAdmin;

class UserAdmin extends AbstractAdmin
{


    protected $entityManager;

    public function setEntityManager(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }


...
}

No comments:

Post a Comment