Last active
August 27, 2025 09:54
-
-
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 π
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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() {} | |
} | |
"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How To Use:
First of, inside,
app/Console/Commands
, create aMakeServiceCommand.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 inService\MyServiceClass.php
.If you wish, you can specify a subfolder to keep things organized:
php artisan make:service Subfolder/MyServiceClass
.