Dieses Blog durchsuchen

Dienstag, 23. August 2016

Symfony3: create a console command and test it

Sometimes you need an easy way to create a console command to add some automation and some admintools to your application. With Symfony3 it is rediculous simple

Install symfony3

Open a console and execute:
$ composer require symfony/symfony

Create a project

Create a project "consoletest" by executing following command on the terminal
$ symfony new consoletest.

Now you have a new project created.

Add your command

Create a file "CreateUserCommand.php" on folder "src/AppBundle/Command" and add following Code
As you can see, this simple command extends from Class Command and implements only 2 methods.
The configure command sets up the command, setup name, description and , prints out helptexts if you want

The execute method does the final work and runs your commandcode. You can manipulate databases, filesystems, get a servicereponse or configure your application with it.

Run your command

At next you can test your command by typing :
$ bin/console app:create-user

You should see your helptext,



Awsome. Isn´t it?

Create a unittest for your command

With symfony it´s very easy to test your new command. Here is a simple test for it:
- Create a folder and a file "test/Appbundle/CreateUserCommandTest.php" with following content in it

And now you can run
$ phpunit symfony

Keine Kommentare:

Kommentar veröffentlichen