num*_*web 3 php factory dependency-injection factory-pattern symfony
Symfony 文档没有给出Symfony 中工厂使用的完整示例。
就我而言,我有许多不同的服务,可以生成不同的水果 API:
每个服务都有自己的依赖项,依赖项是一些绑定参数:
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 方法)使代码变得更好?
| 归档时间: |
|
| 查看次数: |
3442 次 |
| 最近记录: |