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

num*_*web 3 php factory dependency-injection factory-pattern symfony

Symfony 文档没有给出Symfony 中工厂使用的完整示例。

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

  • BananaApi服务
  • 苹果API服务
  • PearApi服务
  • ..

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

services:
    _defaults:
        autowire: true
        bind:
            $guzzleClientBanana: '@eight_points_guzzle.client.banana'
            $guzzleClientApple: '@eight_points_guzzle.client.apple'
            ...
Run Code Online (Sandbox Code Playgroud)

服务举例:

# BananaApiService.php

class BananaApiService extends DefaultEndpointService
{
    protected $guzzleClientBanana;

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

    public function handleRequest(ApiRequest $apiRequest)
    {
    ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

# 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;
                //...
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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