我正在使用控制台命令 Symfony 进行 http 调用。
快速示例工作:
<?php
namespace \App\Command;
use Symfony\Component\Console\Command\Command;
class MainCommand extends Command {
public function __construct(
CallApiService $api,
TekConfiguration $parserConfig,
LoggerInterface $logger,
ParameterBagInterface $param
) {
parent::__construct();
$this->api = $api;
$this->logger = $logger;
$this->parserConfig = $parserConfig;
$this->param = $param;
}
}
<?php
namespace \App\Command;
class FistCommand extends MainCommand{
protected static $defaultName = 'tek:foo:bar';
protected function configure(): void
{
...
}
protected function execute(InputInterface $input, OutputInterface $output)
{
...
$this->api->callFoo();
...
}
}
<?php
namespace App\Tek;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class CallApiService{
public function __construct(HttpClientInterface $tek_api, LoggerInterface $logger)
{
$this->client = $tek_api; //scoped cf. framework.yaml
$this->logger = $logger;
$this->path = $_ENV['API_URL'] . $_ENV['API_PATH'];
... other common conf ...
}
private function get(){
** do call httpclient get **
** and return response **
}
private function post(){
** do call httpclient post **
** and return response **
}
public function callFoo(array $params): array
{
$this->uri = $this->path . '/operations?operation=foo';
return $this->post($params);
}
为了更好地组织我的代码,我想在其他类中外部化 callFoo(和 callBar、callAnother..)方法,该方法将从 CallApiService 继承。喜欢 :
src\Tek\CallApiService.php
src\Tek\Foo\FooCall.php
src\Tek\Bar\BarCall.php
但我不明白如何通过依赖注入来避免重新声明构造函数