80

我需要将两个对象注入ImageService. 其中一个是 的实例Repository/ImageRepository,我得到这样的:

$image_repository = $container->get('doctrine.odm.mongodb')
    ->getRepository('MycompanyMainBundle:Image');

那么如何在我的 services.yml 中声明呢?这是服务:

namespace Mycompany\MainBundle\Service\Image;

use Doctrine\ODM\MongoDB\DocumentRepository;

class ImageManager {
    private $manipulator;
    private $repository;

    public function __construct(ImageManipulatorInterface $manipulator, DocumentRepository $repository) {
        $this->manipulator = $manipulator;
        $this->repository = $repository;
    }

    public function findAll() {
        return $this->repository->findAll();
    }

    public function createThumbnail(ImageInterface $image) {
        return $this->manipulator->resize($image->source(), 300, 200);
    }
}
4

6 回答 6

106

对于像我这样来自 Google 的人来说,这是一个干净的解决方案:

更新:这是 Symfony 2.6(及更高版本)的解决方案:

services:

    myrepository:
        class: Doctrine\ORM\EntityRepository
        factory: ["@doctrine.orm.entity_manager", getRepository]
        arguments:
            - MyBundle\Entity\MyClass

    myservice:
        class: MyBundle\Service\MyService
        arguments:
            - "@myrepository"

推荐使用的解决方案(Symfony 2.5 及更低版本):

services:

    myrepository:
        class: Doctrine\ORM\EntityRepository
        factory_service: doctrine.orm.entity_manager
        factory_method: getRepository
        arguments:
            - MyBundle\Entity\MyClass

    myservice:
        class: MyBundle\Service\MyService
        arguments:
            - "@myrepository"
于 2013-12-03T10:39:15.433 回答
46

我找到了这个链接,这对我有用:

parameters:
    image_repository.class:            Mycompany\MainBundle\Repository\ImageRepository
    image_repository.factory_argument: 'MycompanyMainBundle:Image'
    image_manager.class:               Mycompany\MainBundle\Service\Image\ImageManager
    image_manipulator.class:           Mycompany\MainBundle\Service\Image\ImageManipulator

services:
    image_manager:
        class: %image_manager.class%
        arguments:
          - @image_manipulator
          - @image_repository

    image_repository:
        class:           %image_repository.class%
        factory_service: doctrine.odm.mongodb
        factory_method:  getRepository
        arguments:
            - %image_repository.factory_argument%

    image_manipulator:
        class: %image_manipulator.class%
于 2012-09-01T00:31:40.147 回答
41

如果不想将每个存储库定义为服务,则从版本开始,2.4您可以执行以下操作,(default是实体管理器的名称):

@=service('doctrine.orm.default_entity_manager').getRepository('MycompanyMainBundle:Image')
于 2014-09-01T04:07:23.643 回答
20

Symfony 3.3、4 和 5 让这变得简单多了。

查看我的帖子How to use Repository with Doctrine as Service in Symfony以获得更一般的描述。

对于您的代码,您需要做的就是使用组合而不是继承——这是一种 SOLID 模式。

1.创建自己的仓库,不直接依赖Doctrine

<?php

namespace MycompanyMainBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;
use MycompanyMainBundle\Entity\Image;

class ImageRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(Image::class);
    }

    // add desired methods here
    public function findAll()
    {
        return $this->repository->findAll();
    }
}

2. 使用基于 PSR-4 的自动注册添加配置注册

# app/config/services.yml
services:
    _defaults:
        autowire: true

    MycompanyMainBundle\:
        resource: ../../src/MycompanyMainBundle

3. 现在您可以通过构造函数注入在任何地方添加任何依赖项

use MycompanyMainBundle\Repository\ImageRepository;

class ImageService
{
    public function __construct(ImageRepository $imageRepository)
    {
        $this->imageRepository = $imageRepository;
    }
}
于 2017-10-21T11:36:14.913 回答
1

对于 Symfony 5,这真的很简单,不需要 services.yml 来注入依赖:

  1. 在服务构造函数中注入实体管理器
private $em;

public function __construct(EntityManagerInterface $em)
{
    $this->em = $em;
}
  1. 然后获取存储库:

$this->em->getRepository(ClassName::class)

通过将 ClassName 替换为您的实体名称。

于 2021-06-24T11:43:13.373 回答
0

在我的案例中,基于@Tomáš Votruba 的回答和这个问题,我提出了以下方法:

适配器方法

没有继承

  1. 创建一个通用适配器类:

    namespace AppBundle\Services;
    use Doctrine\ORM\EntityManagerInterface;
    
    class RepositoryServiceAdapter
    {
        private $repository=null;
    
        /**
        * @param EntityManagerInterface the Doctrine entity Manager
        * @param String $entityName The name of the entity that we will retrieve the repository
        */
        public function __construct(EntityManagerInterface $entityManager,$entityName)
        {
            $this->repository=$entityManager->getRepository($entityName)
        }
    
        public function __call($name,$arguments)
        {
          if(empty($arrguments)){ //No arguments has been passed
            $this->repository->$name();
          } else {
            //@todo: figure out how to pass the parameters
            $this->repository->$name(...$argument);
          }
        }
    }
    
  2. 然后为每个实体定义一个服务,例如在我的例子中定义一个(我使用php来定义symfony服务):

     $container->register('ellakcy.db.contact_email',AppBundle\Services\Adapters\RepositoryServiceAdapter::class)
      ->serArguments([new Reference('doctrine'),AppBundle\Entity\ContactEmail::class]);
    

有继承

  1. 与上述步骤 1 相同

  2. 扩展RepositoryServiceAdapter类例如:

    namespace AppBundle\Service\Adapters;
    
    use Doctrine\ORM\EntityManagerInterface;
    use AppBundle\Entity\ContactEmail;
    
    class ContactEmailRepositoryServiceAdapter extends RepositoryServiceAdapter
    {
      public function __construct(EntityManagerInterface $entityManager)
      {
        parent::__construct($entityManager,ContactEmail::class);
      }
    }
    
  3. 注册服务:

    $container->register('ellakcy.db.contact_email',AppBundle\Services\Adapters\RepositoryServiceAdapter::class)
      ->serArguments([new Reference('doctrine')]);
    

如果您有一个很好的可测试方法来测试您的数据库行为,它也可以帮助您模拟,以防您想要对您的服务进行单元测试,而无需过多担心如何做到这一点。例如,假设我们有以下服务:

//Namespace definitions etc etc

class MyDummyService
{
  public function __construct(RepositoryServiceAdapter $adapter)
  {
    //Do stuff
  }
}

并且 RepositoryServiceAdapter 适应以下存储库:

//Namespace definitions etc etc

class SomeRepository extends \Doctrine\ORM\EntityRepository
{
   public function search($params)
   {
     //Search Logic
   }
}

测试

因此,您可以通过模拟非继承方法或继承方法来轻松模拟/硬编码/模拟search定义的方法的行为。SomeRepositoryRepositoryServiceAdapterContactEmailRepositoryServiceAdapter

工厂方法

或者,您可以定义以下工厂:

namespace AppBundle\ServiceFactories;

use Doctrine\ORM\EntityManagerInterface;

class RepositoryFactory
{
  /**
  * @param EntityManagerInterface $entityManager The doctrine entity Manager
  * @param String $entityName The name of the entity
  * @return Class
  */
  public static function repositoryAsAService(EntityManagerInterface $entityManager,$entityName)
  {
    return $entityManager->getRepository($entityName);
  }
}

然后通过执行以下操作切换到 php 服务注释:

将其放入文件./app/config/services.php中(对于 symfony v3.4,.假定您的 ptoject 的根目录)

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
$definition = new Definition();

$definition->setAutowired(true)->setAutoconfigured(true)->setPublic(false);

// $this is a reference to the current loader
$this->registerClasses($definition, 'AppBundle\\', '../../src/AppBundle/*', '../../src/AppBundle/{Entity,Repository,Tests,Interfaces,Services/Adapters/RepositoryServiceAdapter.php}');


$definition->addTag('controller.service_arguments');
$this->registerClasses($definition, 'AppBundle\\Controller\\', '../../src/AppBundle/Controller/*');

并且 cange ./app/config/config.yml.假设您的 ptoject 的根)

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    #Replace services.yml to services.php
    - { resource: services.php }

#Other Configuration

然后您可以按如下方式关闭服务(在我使用名为 的虚拟实体的示例中使用Item):

$container->register(ItemRepository::class,ItemRepository::class)
  ->setFactory([new Reference(RepositoryFactory::class),'repositoryAsAService'])
  ->setArguments(['$entityManager'=>new Reference('doctrine.orm.entity_manager'),'$entityName'=>Item::class]);

同样作为一个通用技巧,切换到php服务注释可以让您轻松完成上述更高级的服务配置。对于代码片段,请使用我使用该方法制作的特殊存储库。factory

于 2018-10-06T09:58:17.350 回答