输入和输出类的 Symfony 依赖注入

And*_*ies 2 symfony

对于我正在开发的一个项目,使用我很陌生的 Symfony,我试图创建一个使用依赖注入但也需要一些自定义参数的类的对象。

现在假设我有一个命令:

<?php

class ServerCommand extends Command {
    public function __construct(Server $server) {
        $this->server = $server;
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一个服务器类:

<?php
class Server {
    public function __construct(MessageManager $messageManager, InputInterface $input, OutputInterface $output) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,Server类被注入到Command类中,MessageManager类被注入到Server类中。

我遇到的问题是将类中的$input$ouput变量Command放入服务器类的构造函数中。

为了使它变得更加困难,我还希望在类中可以访问$input和变量。$outputMessageManager

这可能吗?如果可以,我该如何实现这一目标?

Tom*_*uba 8

编辑:SymfonyStyle实际上只使用Input,但不允许访问它。你到底需要什么Input?您应该仅使用它在Command.


那么,基本上您需要InputOutput作为服务吗?

将它们结合起来的类被称为SymfonyStyle,它是在 Symfony 2.8 中通过一篇不错的博客文章引入的。

有很多方法可以获取输入/输出SymfonyStyle,但我将向您展示最直接的一种。我在Symplify软件包和Rector中使用它已经超过 3 年了,它非常可靠。

<?php declare(strict_types=1);

namespace App\Console;

use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Style\SymfonyStyle;

final class SymfonyStyleFactory
{
    public function create(): SymfonyStyle
    {
        $input = new ArgvInput();
        $output = new ConsoleOutput();

        return new SymfonyStyle($input, $output);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将此工厂注册为服务:

# app/config/services.yaml
services:
    App\Console\SymfonyStyleFactory: ~

    Symfony\Component\Console\Style\SymfonyStyle:
        factory: ['@App\Console\SymfonyStyleFactory', 'create']
Run Code Online (Sandbox Code Playgroud)

然后只需SymfonyStyle在您需要的任何服务中 require 并使用它:

<?php declare(strict_types=1); 

class MessageManager
{
    /**
     * @var SymfonyStyle
     */
    private $symfonyStyle;

    public function __construct(SymfonyStyle $symfonyStyle)
    {
        $this->symfonStyle = $symfonyStyle;
    }

    public function run()
    {
        // some code
        $this->symfonyStyle->writeln('It works!');
        // some code
    }
}
Run Code Online (Sandbox Code Playgroud)