Symfony 2: Creating a service from a Repository Symfony 2: Creating a service from a Repository symfony symfony

Symfony 2: Creating a service from a Repository


DEPRECATION WARNING: No more factory_service and factory_method. This is how you should do it since Symfony 2.6 (for Symfony 3.3+ check below):

parameters:    entity.my_entity: "AppBundle:MyEntity"services:    my_entity_repository:        class: AppBundle\Repository\MyEntityRepository        factory: ["@doctrine", getRepository]        arguments:            - %entity.my_entity%

The new setFactory() method was introduced in Symfony 2.6. Refer to older versions for the syntax for factories prior to 2.6.

http://symfony.com/doc/2.7/service_container/factories.html

EDIT: Looks like they keep changing this, so since Symfony 3.3 there's a new syntax:

# app/config/services.ymlservices:    # ...    AppBundle\Email\NewsletterManager:        # call the static method        factory: ['AppBundle\Email\NewsletterManagerStaticFactory', createNewsletterManager]

Check it out: http://symfony.com/doc/3.3/service_container/factories.html


Here is how we did it in KnpRadBundle: https://github.com/KnpLabs/KnpRadBundle/blob/develop/DependencyInjection/Definition/DoctrineRepositoryFactory.php#L9

Finally it should be:

my_service:    class: Doctrine\Common\Persistence\ObjectRepository    factory_service: doctrine # this is an instance of Registry    factory_method: getRepository    arguments: [ %mytest.entity% ]

UPDATE

Since 2.4, doctrine allows to override the default repositor factory.

Here is a possible way to implement it in symfony: https://gist.github.com/docteurklein/9778800


You may have used the wrong YAML-Keys. Your first configuration works fine for me using

  • factory_service instead of factory-service
  • factory_method instead of factory-method