Подтвердить что ты не робот

Как вставить репозиторий в службу в Symfony2?

Мне нужно ввести два объекта в 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);
    }
}
4b9b3361

Ответ 1

Я нашел ссылку , и это сработало для меня:

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%

Ответ 2

Вот очищенное решение для тех, кто приходит от 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"

Ответ 3

Если вы не хотите определять каждый репозиторий как услугу, начиная с версии 2.4, вы можете сделать следующее, (default - это имя диспетчера сущностей):

@=service('doctrine.orm.default_entity_manager').getRepository('MycompanyMainBundle:Image')

Ответ 4

2017 и Symfony 3.3 + сделали это намного проще.

Отметьте мой пост Как использовать репозиторий с Doctrine как услугу в 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;
    }
}