php 生成interfalce和repository
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class RepositoryMaker extends Command
{
protected $signature = 'make:repository {model}';
protected $description = '生成repository的interfalce和eloquent';
public function handle()
{
$model = $this->argument('model');
$base = __DIR__ . '/../../Repository/';
$this->makeInterface($model, $base);
$this->makeEloquent($model, $base);
}
public function makeInterface($model, $base)
{
$path = "${base}Interfaces/${model}Repository.php";
if (file_exists($path)) {
$this->error('已经存在接口');
return;
}
$template = $this->interfaceTemplate;
$this->generate($path, $template, $model);
}
public function makeEloquent($model, $base)
{
$path = "${base}Eloquents/${model}Repository.php";
if (file_exists($path)) {
$this->error('已经存在实现');
return;
}
$template = $this->eloquentTemplate;
$this->generate($path, $template, $model);
}
public function generate($path, $template, $model)
{
$content = str_replace('__MODEL__', $model, $template);
file_put_contents($path, $content);
}
public $interfaceTemplate = <<<EOF
<?php
namespace App\Repository\Interfaces;
interface __MODEL__Repository
{
//
}
EOF;
public $eloquentTemplate = <<<EOF
<?php
namespace App\Repository\Eloquents;
use App\Models\__MODEL__;
use App\Repository\Interfaces\__MODEL__Repository as __MODEL__Interface;
class __MODEL__Repository implements __MODEL__Interface
{
//
}
EOF;
}