我正在尝试使用自定义命令创建一个服务类。
目前,如果我运行
php artisan make:service TestService
,它将在Services文件夹中使用命名空间App\Services
生成,但如果我运行php artisan make:service Test/TestService
,它将在Services/Test文件夹中生成,但命名空间仍然是App\Service
,实际上应该是 App\Services\Test
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class MakeService extends GeneratorCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:service {name}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a Service class';
public function getStub()
{
return app_path() . '/Console/Commands/Stubs/make-service.stub';
}
public function getDefaultNamespace($rootNamespace)
{
return $rootNamespace . '\Services';
}
public function replaceClass($stub, $name)
{
$class = str_replace($this->getNamespace($name) . '\\', '' $name);
return str_replace('{{ service_name }}', $class, $stub);
}
}
我的存根
<?php
namespace App\Services;
class {{ service_name }}
{
public function __construct()
{
}
}
您需要做的是将用户的输入除以字符 / 并取出除最后一个之外的所有部分
示例
public function replaceClass($stub, $name)
{
$name_parts = explode('/','Test/TestService');
$class_name = $name_parts[count($name_parts)-1];
$namespace = implode("\\", array_slice($name_parts, 0, -1));
$namespace = $namespace !== "" ? "\\". $namespace : ""; // if extra namespace exist prepend with \
$stub = str_replace('{{ service_name }}', $class_name, $stub); // inject class name
$stub = str_replace('{{ service_namespace }}', $namespace, $stub); // inject namespace
return $stub
}
显然存根变成了
<?php
namespace App\Services{{ service_namespace }};
class {{ service_name }}
{
public function __construct()
{
}
}