Skip to content

Instantly share code, notes, and snippets.

@jovialcore
Last active August 27, 2025 09:54
Show Gist options
  • Save jovialcore/344c06ad3b3f46d927f29d42442e18dd to your computer and use it in GitHub Desktop.
Save jovialcore/344c06ad3b3f46d927f29d42442e18dd to your computer and use it in GitHub Desktop.
If you use services class for your logic, this command script lets you easily create a service class. See comment for instructions πŸ‘‡
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputArgument;
class MakeServiceCommand extends GeneratorCommand
{
protected $name = 'make:service';
protected $description = 'Create a new service class';
protected $type = 'Service';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub(): string
{
$this->createStub();
return $this->getStubPath();
}
protected function getStubPath(): string
{
return __DIR__ . '/Stubs/ServiceStubs/service.stub';
}
/**
* Get the default namespace for the class.
*
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace): string
{
return $rootNamespace . '\Services';
}
/**
*
* @return array <array>
*/
protected function getArguments(): array
{
return [
['name', InputArgument::REQUIRED, 'The name of the service class'],
];
}
/**
* Create the stub file
* @return void
*/
protected function createStub(): void
{
$path = $this->getStubPath();
$realPath = $this->makeDirectory($path);
$this->files->put($realPath, $this->getStubContent());
}
/**
* Get the stub content
*
* @return string
*/
private function getStubContent(): string {
return "<?php
namespace {{ namespace }};
class {{ class }}
{
public function __construct() {}
}
";
}
}
@jovialcore
Copy link
Author

jovialcore commented Aug 27, 2025

How To Use:

First of, inside, app/Console/Commands, create a MakeServiceCommand.php file. then paste the code in this gist into the file you just created.

Next,
Run php artisan make:service MyServiceClass. The file by default will be created in Service\MyServiceClass.php.
If you wish, you can specify a subfolder to keep things organized: php artisan make:service Subfolder/MyServiceClass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment