stubsの作成
mkdir -p プロジェクトルート/stubs
touch プロジェクトルート/stubs/service.stub
touch プロジェクトルート/stubs/service.interface.stub
service.stub
<?php
namespace {{ namespace }};
class {{ class }}Service
{
/**
* Create a new service instance.
*/
public function __construct()
{
//
}
}
service.interface.stub
<?php
namespace {{ namespace }}\Interfaces;
interface {{ class }}ServiceInterface
{
//
}
chmod 644 プロジェクトルート/stubs/service.stub
chmod 644 プロジェクトルート/stubs/service.interface.stub
コマンド作成
php artisan make:command MakeServiceCommand
app/Console/Commands/MakeServiceCommand.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class MakeServiceCommand extends Command
{
protected $signature = 'make:service {name} {--i : Create with interface}';
protected $description = 'Create a new service class';
public function handle()
{
$name = $this->argument('name');
$withInterface = $this->option('i');
// サービスクラスの作成
$this->createService($name, $withInterface);
if ($withInterface) {
$this->createInterface($name);
}
$this->info('Service created successfully!');
return Command::SUCCESS;
}
private function createService($name, $withInterface)
{
$stub = File::get(base_path('stubs/service.stub'));
$stub = str_replace(
['{{ namespace }}', '{{ class }}'],
['App\\Services', $name],
$stub
);
if ($withInterface) {
$stub = str_replace(
"class {$name}Service\n{",
"use App\\Services\\Interfaces\\{$name}ServiceInterface;\n\nclass {$name}Service implements {$name}ServiceInterface\n{",
$stub
);
}
$path = app_path("Services/{$name}Service.php");
$this->ensureDirectoryExists(dirname($path));
File::put($path, $stub);
}
private function createInterface($name)
{
$stub = File::get(base_path('stubs/service.interface.stub'));
$stub = str_replace(
['{{ namespace }}', '{{ class }}'],
['App\\Services', $name],
$stub
);
$path = app_path("Services/Interfaces/{$name}ServiceInterface.php");
$this->ensureDirectoryExists(dirname($path));
File::put($path, $stub);
}
private function ensureDirectoryExists($directory)
{
if (!File::exists($directory)) {
File::makeDirectory($directory, 0755, true);
}
}
}
使用方法
サービスクラスの作成
php artisan make:service サービスの名前
インターフェース付きでサービスクラスを作成
php artisan make:service サービスの名前 --i