在代码中使用Symfony Service,是否可以不转发参数



我知道,我可以简单地在控制器和命令中使用服务。

但是如果我有像这样复杂的嵌套体系结构

// Controller
public function testUrl()
{
(new ProcessorA())->process();
}
// ProcessorA
public function process()
{
(new ProcessorB())->process();
}
// a lot of nested calls of processors (A, B, C ... Z)
// ProcessorZ
public function process()
{
(new RedisService())->call(); // <- HOW CAN I GET RedisService THERE?
}

我的注册服务:

AppServiceRedisService:
class: AppServiceRedisService
bind:
$host: '%env(resolve:REDIS_HOST)%'
$port: '%env(resolve:REDIS_PORT)%'

App\Service\RedisService:

namespace AppService;
class RedisService extends PredisClient
{
public function __construct(string $host, string $port)
{
parent::__construct(['host' => $host, 'port' => $port], []);
}
public function call() { ....}
}

问题:有没有一种方法可以在不转发的情况下通过BestPractice获得代码深度的服务(RedisService(?或者我必须通过构造函数将服务从Controller转发到ProcessorZ?

// Controller
public function testUrl(RedisService $redis)
{
(new ProcessorA($redis))->process();
}
// ProcessorA
public function process()
{
(new ProcessorB($this->redis))->process();
}
// a lot of processors
// ProcessorZ
public function process()
{
$this->redis->call();
}

您可以像将RedisService注册为服务一样,将ProcessorZ注册为服务(或任何处理器(。就像您将$host和$port参数绑定到RedisService一样,您也可以将RedisService绑定到ProcessorZ类。

https://symfony.com/doc/current/service_container.html#service-参数

在您的情况下

services:
AppServiceProcessorZ:
arguments:
# this is not a string, but a reference to a service
- '@AppServiceRedisService'

在您的ProcessorZ.php 中

...
class ProcessorZ {
private RedisService $redisService;

public function __construct(RedisService $redisService) {
$this->redisService = $redisService;
}

public function process()
{
$this->redisService->call();
}
}

通过使用自动布线和自动配置,这个过程可以更简单、更快,所以你可能想在这里看看:https://symfony.com/doc/current/service_container/autowiring.html

相关内容

最新更新