【问题标题】:How to Inject Services in another Service using Factory to create them如何使用工厂在另一个服务中注入服务来创建它们
【发布时间】:2018-07-03 22:17:04
【问题描述】:

我在 symfony 4.1 中创建服务时遇到了一点问题

我使用工厂来创建我的服务,并强制工厂拥有我制作接口的预期方法

<?php

namespace App\Service\Factory\Interfaces;


use App\Service\Interfaces\BaseModelServiceInterface;
use Doctrine\ODM\MongoDB\DocumentManager;

/**
 * Interface ModelServiceFactoryInterfaces
 * @package App\Service\Factory\Interfaces
 */
interface ModelServiceFactoryInterfaces
{

    /**
     * Create the Model related Service
     *
     * @return BaseModelServiceInterface
     */
    public function createService(DocumentManager $dm);

}

我从自动装配的服务中获取 DocumentManager 以在工厂中创建存储库并将其传递给服务,就像这样

/**
 * Class ChapterServiceFactory
 * @package App\Service\Factory
 */
class ChapterServiceFactory implements ModelServiceFactoryInterfaces
{
    /**
     * @param DocumentManager $dm
     * @return ChapterService|BaseModelServiceInterface
     */
    public function createService(DocumentManager $dm)
    {
        $chapterRepository = $dm->getRepository(Chapter::class);
        /**
         * @var $chapterRepository ChapterRepository
         */
        return new ChapterService($chapterRepository);
    }

}

问题在于,如果我想在我的 ChapterService 中有另一个服务,我不能因为接口而在工厂中自动装配它,但我也不想删除接口。

有没有办法让接口拥有“动态参数”,或者除了接口之外的其他方式来强制工厂拥有 createService 方法?

【问题讨论】:

    标签: symfony dependency-injection factory symfony4


    【解决方案1】:

    对此没有解决方法:如果将接口声明为参数,则需要为该接口提供显式实现。这意味着您不能为同一个接口声明两个默认实现。在这种情况下,您唯一能做的就是显式声明服务及其所有参数。

    顺便说一句,当您正在撰写有关 Doctrine Repositories 的文章时,我建议您查看ServiceEntityRepository:从您的一个存储库扩展此类将自动使报告成为您可以在需要时注入的服务。

    【讨论】:

    • 好的,如果我想要其他服务,我需要删除接口(或制作另一个重新定义方法的接口),对吧?我使用 Doctrine ODM,但我没有看到 ServiceEntityRepository 的任何等效项。该功能是几个月前开始的,但没有任何消息。
    • @Etshy 我更愿意保留接口(如果行为相同,则保持相同)并明确声明服务 tbh。
    • 好的,所以如果我在服务中需要另一个服务,我会为此创建一个特定的接口(因为我的大部分服务都只有一个存储库)。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2018-08-28
    • 1970-01-01
    • 2013-12-22
    • 2014-01-27
    • 1970-01-01
    相关资源
    最近更新 更多