Symfony 工厂:注入依赖、自动装配和绑定参数

Symfony factories: injecting dependencies, autowiring and binding parameters

Symfony 中工厂的使用Symfony docs don't give a full example

就我而言,我有许多不同的服务,可以生成不同的水果 API:

每个服务都有自己的依赖,依赖是一些绑定参数:

services:
    _defaults:
        autowire: true
        bind:
            $guzzleClientBanana: '@eight_points_guzzle.client.banana'
            $guzzleClientApple: '@eight_points_guzzle.client.apple'
            ...

服务示例:

# BananaApiService.php

class BananaApiService extends DefaultEndpointService
{
    protected $guzzleClientBanana;

    public function __construct(GuzzleClient $guzzleClientBanana)
    {
        $this->guzzleClientBanana = $guzzleClientBanana;
    }

    public function handleRequest(ApiRequest $apiRequest)
    {
    ...
    }
}

目前我没有使用工厂模式,而是将所有服务传递给经理的构造函数,这太脏了并且违反了最佳实践:

# ApisManagerService

class ApisManagerService
{
    protected $BananaApiService;
    protected $AppleApiService;
    protected $PearApiService;

    public function __construct(BananaApiService $BananaApiService, 
                                AppleApiService $AppleApiService, 
                                PearApiService $PearApiService)
    {
        $this->BananaApiService = $BananaApiService;
        //...
    }

    public function requestDispatcher(ShoppingList $shoppingList): void
    {
        foreach ($shoppingList->getItems() as $item) {
            switch ($item->getName()) {
                case 'banana':
                    $this->BananaApiService->handleRequest($item);
                    break;
                case 'apple':
                    $this->AppleApiService->handleRequest($item);
                    break;
                //...
            }
        }
    }
}

此 requestDispatcher 是通过某个事件订阅者调用的:

class EasyAdminSubscriber implements EventSubscriberInterface
{

    public function triggerApisManagerService(GenericEvent $event): void
    {
        /* @var $entity shoppingList */
        $entity = $event->getSubject();

        if (! $entity instanceof shoppingList) {
            return;
        }

        $this->apisManagerService->requestDispatcher($entity);
    }
}

如何使用 Symfony 工厂(或其他 Symfony 方法)使代码更好?

我建议看一下 strategy pattern 针对此特定案例的实施。这将是一种比所有服务构造函数注入更清洁的解决方案,特别是在不需要使用所有服务的情况下 - 使用策略模式您将仅使用所需的服务(在应用程序 运行 时) , & 处理它们的特定逻辑。