【问题标题】:Access Command OutputInterface within a Doctrine Fixtures Load在 Doctrine Fixtures 加载中访问命令输出接口
【发布时间】:2014-10-08 02:17:57
【问题描述】:

我正在使用很棒的Faker Library 生成大量数据固定装置,还使用lorempixel.com 在我的 Symfony2 项目中生成一些随机图像。这需要一些时间(目前约 10 分钟),所以我想知道是否可以通过容器接口以某种方式访问​​ Command OutputInterface 并以这种方式打印进度而不是 echo'ing 一切..

也许还可以通过ProgressBar 获得不错的输出

【问题讨论】:

  • 我正在更新 DoctrineMigration 类中的一个大型数据库,我想要一个进度条。你找到解决这个问题的办法了吗?
  • 不幸的是没有使用 DoctrineMigrations - 我发现唯一合适的方法是编写自己的命令并在那里实现逻辑而不是迁移类..

标签: php symfony doctrine-orm command


【解决方案1】:

看起来ConsoleOutput不需要什么特别的东西,可以直接实例化。

use Symfony\Component\Console\Output\ConsoleOutput;

// ...

public function load(ObjectManager $manager)
{
    $output = new ConsoleOutput();

    $output->writeln('<info>this works... </info>');
} 

【讨论】:

  • 过了这么久。我什至没有尝试简单地创建 ConsoleOutput 的实例 - 感谢您解开这个谜
  • 中有错字
【解决方案2】:

如果您使用ConsoleEvents::COMMAND 事件获得“原始”$output 对象,可能会得到更好的解决方案。

namespace App\DoctrineFixtures;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CustomFixture extends AbstractFixture implements EventSubscriberInterface
{
    /** @var OutputInterface */
    private $output;

    /** @var Command */
    private $command;

    public static function getSubscribedEvents()
    {
        return [
            ConsoleEvents::COMMAND => 'init',
        ];
    }

    public function init(ConsoleCommandEvent $event): void
    {
        $this->output = $event->getOutput();
        $this->command = $event->getCommand();
    }

    public function load(ObjectManager $manager)
    {
        // ...
        $this->output->writeln('...');
        // ...
        $tableHelper = $this->command->getHelper('table');
        // ...
        $progressBar = new ProgressBar($this->output, 50);
        // ...
    }
}

services.yml:

services:
    App\DoctrineFixtures\CustomFixture:
        tags:
            - 'doctrine.fixture.orm'
            - 'kernel.event_subscriber'

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多