Мне нужно ввести два объекта в 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);
}
}
Я нашел ссылку , и это сработало для меня:
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%
Вот очищенное решение для тех, кто приходит от 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"
doctrine.odm.mongodb.document_manager
как factory_service
$this->get('myrepository')
работает, но делает любые репозитории, которые вы добавляете таким образом, доступными через контроллеры с $this->get('myrepository')
. Есть ли способ определить / передать хранилище в качестве аргумента myservice
не определяя его как саму службу?
Если вы не хотите определять каждый репозиторий как услугу, начиная с версии 2.4
, вы можете сделать следующее, (default
- это имя диспетчера сущностей):
@=service('doctrine.orm.default_entity_manager').getRepository('MycompanyMainBundle:Image')
2017 и Symfony 3.3 + сделали это намного проще.
Отметьте мой пост Как использовать репозиторий с Doctrine как услугу в Symfony для более общего описания.
В ваш код все, что вам нужно сделать, это использовать композицию над наследованием - один из SOLID-шаблонов.
<?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();
}
}
# app/config/services.yml
services:
_defaults:
autowire: true
MycompanyMainBundle\:
resource: ../../src/MycompanyMainBundle
use MycompanyMainBundle\Repository\ImageRepository;
class ImageService
{
public function __construct(ImageRepository $imageRepository)
{
$this->imageRepository = $imageRepository;
}
}