php - 当方法需要参数时,如何在 Symfony 4.3.x 中正确地自动连接接口(interface)?

标签 php symfony symfony-4.3

我正在尝试构建一个 Symfony 4.3.3 命令,我想在其中添加随时覆盖回调函数的功能。看下面的代码片段:

namespace App\Command;

use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\WebSocket\Server;

final class SwooleWsCommand extends Command
{
    // ...

    protected function execute(InputInterface $input, OutputInterface $output): bool
    {
        $port   = $input->getArgument('port');
        $server = new SwooleServer("127.0.0.1", (int)$port);
        $server->on('request', static function (Request $request, Response $response) {
            $response->end('Hello '.$request->rawcontent());
        });
        $server->start();
        return true;
    }
}

我想转换这个:

$server->on('request', static function (Request $request, Response $response) {
    $response->end('Hello '.$request->rawcontent());
});

对此(如果可能并且这不是一件疯狂的事情或不可能实现的事情):

$server->on('request', <function>);

我的想法(也许我完全错了)是创建一个允许方法随时被覆盖的接口(interface)。下面是它的代码片段:

namespace App\Service;

use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

interface SwooleWsCallbackInterface
{
    public function request(Request $request, Response $response): void;
    public function message(Server $server, Frame $frame): void;
}

从那里我应该能够在命令中注入(inject)接口(interface),例如:

/** @var SwooleWsCallbackInterface */
private $callback;

public function __construct(SwooleWsCallbackInterface $callback)
{
    $this->callback = $callback;
    parent::__construct();
}

您可能会注意到函数 request() 接收两个参数。出于这样的原因,一旦我从命令中调用方法 $server->on('request', $this->callback->request($request, $response)); 它会尝试访问两个参数。

我已阅读 How to Autowire Interfaces 的 Symfony 文档但我仍然不清楚如何正确设置该方法所需的参数。

如果我在这里正确理解文档:

 App\Util\TransformerInterface: '@App\Util\Rot13Transformer'

他们已经覆盖了 App\Util\Rot13Transformer 中的方法,应该不会有任何问题。但是,该示例未显示调用接口(interface) TransformerInterface 中的方法 transform

不确定在我的场景中正确的 Autowiring 是否是:

  App\Command\SwooleWsCommand: ~
  sdk.command.swoolews:
    alias: App\Command\SwooleWsCommand

  App\Service\SwooleWsCallbackInterface: ~
  sdk.swoolews:
    alias: App\Service\SwooleWsCallbackInterface

我可以在这里得到一些关于如何实现这一目标的想法吗?以及它如何工作的一些解释?我可能弄错了:|

Note: if something is not clear or it's confusing just ask me

最佳答案

您仍想创建一个闭包以传递给 $server->on。您可以这样做:

$onRequest = Closure::fromCallable([$this->callback, 'request']);

然后传递给它:

$server->on('request', $onRequest);

关于php - 当方法需要参数时,如何在 Symfony 4.3.x 中正确地自动连接接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57500936/

相关文章:

php - Phalcon 选择要安装的版本

javascript - 在ajax中分组结果查询

symfony - 用户密码字段的最大长度为 "algorithm: auto"?

php - 唯一约束返回类型不匹配

php - 使用 CodeIgniter 插入语句——太困惑了

php - 如何使用 XMLHttpRequest 传递 php session

php - 使用 Symfony 覆盖 config_dev 中的 mapping_types 部分

symfony - 停留在prePersist功能时如何取消保存实体

php - Symfony2/学说 : how to add more of the same entity in the same collection?