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
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
protected $commands = [ Commands\MakeServiceCommand::class, ];
Once you are done, open up
MakeServiceCommand class, and refer to gist below.
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.
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
protected $description = 'Create a new Service class';is the description of the artisan command you want to create.
protected $type = 'Service';will be use by generator to display message on successful creation of the class.
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.
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/Serviceswith namespace of
Stub is like a template for your class generator to be make of, but the most important part is:
namespace DummyNamespace;required as this will generated real namespace of your class.
DummyClassrequired 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.