How can I inject doctrine into Symfony2 service

后端 未结 1 902
孤街浪徒
孤街浪徒 2021-02-10 04:03

I use simplified controller and have no service container. I\'m trying to inject doctrine into a service. Here is the error:

ContextErrorException: Catchable Fat         


        
1条回答
  •  無奈伤痛
    2021-02-10 05:03

    The problem is that you're mixing both YAML service definition and DiExtra annotations for the same class. The YAML definition is full and provides the required dependency, but you haven't added @InjectParams to play with the @Service annotation. Basically, you're creating two services of the single class using different approaches and the annotations approach is not complete.

    Either remove the @Service annotation from the class, or, if you prefer annotations (which I do), inject the dependencies with annotations too and get rid of the YAML service definition:

    /**
     * @InjectParams({
     *    "em" = @Inject("doctrine.orm.entity_manager")
     * })
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }
    

    The @InjectParams annotation matches parameter names like $em to service names like @em. Since there is no @em service, you have to override the default matching with the @Inject annotation.

    But there is a way to simplify it. You can alias the entity manager to @em in your YAML configuration file:

    services:
        em:
            alias: doctrine.orm.entity_manager
    

    Now you can simplify the @InjectParams annotation:

    /**
     * @InjectParams
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }
    

    0 讨论(0)
提交回复
热议问题