Symfony文档没有给出Symfony中使用工厂的完整示例。
在我的情况下,我有许多不同的服务,生成不同的水果API,比如:
- BananaApiService
- AppleApiService
- PearApiService
- ..
每个服务都有自己的依赖项,这个依赖项是一些绑定参数:
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方法)使代码更好?