Symfony 如何使用Factory在另一个服务中注入服务以创建它们
我在symfony 4.1中创建服务时遇到了一点问题 我使用工厂来创建我的服务,并强制工厂使用我创建的接口所需的方法Symfony 如何使用Factory在另一个服务中注入服务以创建它们,symfony,dependency-injection,factory,symfony4,Symfony,Dependency Injection,Factory,Symfony4,我在symfony 4.1中创建服务时遇到了一点问题 我使用工厂来创建我的服务,并强制工厂使用我创建的接口所需的方法 <?php namespace App\Service\Factory\Interfaces; use App\Service\Interfaces\BaseModelServiceInterface; use Doctrine\ODM\MongoDB\DocumentManager; /** * Interface ModelServiceFactoryInte
<?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);
}
问题是,如果我想在ChapterService中有另一个服务,由于接口的原因,我不能在工厂中自动连接它,但我也不想删除接口
有没有一种方法可以使接口具有“动态参数”,或者用接口以外的另一种方法强制工厂具有createService方法?没有解决方法:如果将接口声明为参数,则需要为该接口提供显式实现。这意味着您不能为同一接口声明两个默认实现。在这种情况下,您唯一能做的就是显式声明服务及其所有参数
顺便说一句,在您撰写关于条令存储库的文章时,我建议您看看:从一个repo扩展这个类将自动使报表成为一个可以在需要时注入的服务。OK,所以如果我需要其他服务,我需要删除该接口(或者创建另一个重新定义该方法的接口),对吗?我使用了ODM原则,但我没有看到
ServiceEntityRepository
的任何等价性。该功能是几个月前启动的,但没有相关新闻。@Etshy我更愿意保留接口(如果它的行为相同,则保持相同),并显式声明服务tbh。好的,如果我需要服务中的另一个服务,我会为此服务创建一个特定接口(因为我的大多数服务都只有一个存储库)。谢谢。
/**
* 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);
}
}