Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Command OutputInterface within a Doctrine Fixtures Load

I'm generating a huge amount of data fixtures using the awesome Faker Library, also using lorempixel.com to have some random images in my Symfony2 project. This takes some time (currently ~ 10 Minutes), so I was wondering if it is possible to access the Command OutputInterface somehow through the container interface and print the progress this way instead of echo'ing everything..

Maybe also to have a nice output with ProgressBar

like image 393
con Avatar asked Aug 14 '14 12:08

con


2 Answers

It looks like ConsoleOutput doesn't need anything special and can be instantiated directly.

use Symfony\Component\Console\Output\ConsoleOutput;

// ...

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

    $output->writeln('<info>this works... </info>');
} 
like image 200
John Pancoast Avatar answered Nov 14 '22 08:11

John Pancoast


Maybe a little bit better solution if you get the "original" $output object, using the ConsoleEvents::COMMAND event.

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);
        // ...
    }
}

In services.yml:

services:
    App\DoctrineFixtures\CustomFixture:
        tags:
            - 'doctrine.fixture.orm'
            - 'kernel.event_subscriber'
like image 27
Krisztián Ferenczi Avatar answered Nov 14 '22 08:11

Krisztián Ferenczi