Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a symfony 4 command to be registered only in dev environment and disabled in prod?

In my App I have a helper class App\Command\GenerateFixturesCommand that provides a command named my-nice-project:generate-fixtures.

This command consumes a service of my own project named App\Services\CatalogFixtureGenerator that generates 1000 random PDF documents for testing while developing the app.

To do so, this service uses the joshtronic\LoremIpsum class which is required in composer only in dev. LoremIpsum is a third-party library. I require it under composer's require-dev.

So the injection is:

  1. I run my GenerateFixturesCommand.
  2. Before that, the system transparently locates my CatalogFixtureGenerator and to inject it into the command.
  3. Before that, the system transparently locates the LoremIpsum third party service to inject it into my fixture generator service.

All is autowired.

When I deploy to prod and do composer install --no-dev --optimize-autoloader of course the LoremIpsum class is not installed.

But when I clear the cache with APP_ENV=prod php bin/console cache:clear the framework finds the command and cannot inject the autowired dependencies.

[WARNING] Some commands could not be registered:
In CatalogsFixtureGenerator.php line 26:
Class 'joshtronic\LoremIpsum' not found

This my-nice-project:generate-fixtures command is never going to be used in the production server.

Question

How can I "disable" the command in prod?

I mean: How can I tell the framework that the class GenerateFixturesCommand should not be loaded nor its autowired dependencies, and neither of them should be autowired in prod?

like image 609
Xavi Montero Avatar asked May 12 '19 15:05

Xavi Montero


1 Answers

Use the isEnabled() method in Command. For example

    public function isEnabled(): bool
    {
        // disable on prod
        if ($this->appKernel->getEnvironment() === 'prod') {
            return false;
        }

        return true;
    }
like image 126
GusDeCooL Avatar answered Sep 21 '22 18:09

GusDeCooL