Create an artisan command for generating custom classes or files

Tags: , ,



What’s the best way ( or maybe the way it’s actually done ) of creating an artisan command for generating custom classes or files? Like php artisan make:console itself that creates a php class for our new artisan command.

From what I can think of, we have two options:

  • Add the template for that new file using php heredoc(or any string inside the new command’s class file for that matter), which is really messy.

  • Put a template file somewhere, read it, replace what’s necessary, and then create the new file. But I don’t know where would be best to put the template file.

So is there a best-practice for handling this situation in Laravel? I googled it, but there was only articles and documentation for simple artisan command creation.

Answer

Laravel uses .stub files as templates, and replaces the tokens inside the template.

Since you mentioned the make:console command, for reference you can take a look at the following files:

  • vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/console.stub
    (on github)
    This the template for making new console commands.
  • vendor/laravel/framework/src/Illuminate/Foundation/Console/ConsoleMakeCommand.php
    (on github)
    This is the code that is executed when you run the php artisan make:console command.

If you want to take a look at packages that have done this, as well, a good example is the generators package by Jeffrey Way at Laracasts.



Source: stackoverflow