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.
- 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 asmake:service
. I do keep the naming convention start withmake:
. - The
protected $description = 'Create a new Service class';
is the description of the artisan command you want to create. - The
protected $type = 'Service';
will be use by generator to display message on successful creation of the class. - 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. - 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 atapp/Services
with namespace ofApp/Services
.
Stub is like a template for your class generator to be make of, but the most important part is:
- The
namespace DummyNamespace;
required as this will generated real namespace of your class. - 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