Artisan, Laravel

Laravel: Write Class Generator Command

Assalamualaikum,

In this post, I will share with you how you can create your own class generator – like php artisan make:model ....

So here the trick, in order to create your own class generator command, you can extend the use IlluminateConsoleGeneratorCommand.

For instance, you want to create make:service. First, create new artisan command by running

php artisan make:command MakeServiceCommand

This will create a new command class located at app/Console/Commands/ directory. You need to register the command in app/Console/Kernel.php in $commands property.

    protected $commands = [
        CommandsMakeServiceCommand::class,
    ];

Once you are done, open up MakeServiceCommand class, and refer to gist below.

The service.stub should be located in app/Console/Commands/stubs – do create the directory and file if not yet exists.

Here a little bit of explanation.

  1. The protected $name = 'make:service'; is the artisan command you want to use. In this case, we want to make a service class, that’s why we name it as make:service. I do keep the naming convention start with make:.
  2. The protected $description = 'Create a new Service class'; is the description of the artisan command you want to create.
  3. The protected $type = 'Service'; will be use by generator to display message on successful creation of the class.
  4. The protected function getStub() method is a method to get the stub / template how your class will look like. Based on that stub the generator will create the new service class for you. Will explain about stub later.
  5. The protected function getDefaultNamespace($rootNamespace) method basically to define your namespace and also path of your class when created. In this case, will be located at app/Services with namespace of App/Services.

Stub is like a template for your class generator to be make of, but the most important part is:

  1. The namespace DummyNamespace; required as this will generated real namespace of your class.
  2. The DummyClass required as the name your class.

Other methods in the stub can derive / define as you see fit.

So, that is a little bit of how to write your own class generator using artisan command. This is helpful as your application grow big, probably to enterprise level, you will require a lot of automation to reduce human errors.

Hope this article will help you guys manage your Laravel application to be more consistent and manageable.

Thanks,
Nasrul

Leave a Reply

Your email address will not be published. Required fields are marked *

9 − 1 =