# Creating a make:action Command

If you've read the recent Article by Freek Van der Herten where he describes how and why to put logic in Actions, you probably have an itch and want to try this pattern in your next project. The only thing missing is a make:action
command.
Before you open an issue on the Laravel framework, demanding this feature or requiring a composer package, I want to show you how easy it is to create a custom make
command.
# Creating a stub and extending the GeneratorCommand
There are two files needed to create a new make command: a stub and a command that extends Illuminate\Console\GeneratorCommand
. Since actions are very simple classes which usually only have a __construct
and an execute
method, I took the make:listener
command class as a base and changed it to create an action class.
Here's how the ActionMakeClass
looks like:
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class ActionMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:action';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new action class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Action';
/**
* Determine if the class already exists.
*
* @param string $rawName
* @return bool
*/
protected function alreadyExists($rawName)
{
return class_exists($rawName);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/action.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Actions';
}
}
Now we only need the stub which looks like this:
<?php
namespace DummyNamespace;
class DummyClass
{
/**
* Create the action.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the action.
*
* @return void
*/
public function execute()
{
//
}
}
Make sure to move this file to app/Console/Commands/stubs/action.stub
. DummyNamespace
and DummyClass
will automatically be replaced with the given classname and qualified namespace.
Now you can use your command like this:
php artisan make:action NewAction
Like anything else, it is very easy to create a custom make command thanks to some Laravel magic.