如何将存储库注入

如何将存储库注入

本文介绍了如何将存储库注入 Symfony 中的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to inject two objects into ImageService. One of them is an instance of Repository/ImageRepository, which I get like this:

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

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

So how do I declare that in my services.yml? Here is the service:

namespace MycompanyMainBundleServiceImage;

use DoctrineODMMongoDBDocumentRepository;

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);
    }
}

推荐答案

我发现了这个 link 这对我有用:

I found this link and this worked for me:

parameters:
    image_repository.class:            MycompanyMainBundleRepositoryImageRepository
    image_repository.factory_argument: 'MycompanyMainBundle:Image'
    image_manager.class:               MycompanyMainBundleServiceImageImageManager
    image_manipulator.class:           MycompanyMainBundleServiceImageImageManipulator

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%

这篇关于如何将存储库注入 Symfony 中的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:38