There is a category of laravel devs that seperate project logic into a service class. Some devs also call it actions.
Even though Laravel ships with a couple handful commands, we don’t have the services command yet so I decided to create one since I often export my core logic in a service class.
This command will help automate the dreary process of creating a service class.
Other : First timer experience using PHPStorm
It’s a one file laravel command logic. To use: First of, inside, app/Console/Commands, create a MakeServiceCommand.php file then paste the code below into the file you just created.
<?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() {}
}
";
}
}I hope this helps with bootstraping a service class. Happy Coding!
Feel free to drop your questions.
Leave a Reply