目的:為了方便的快速創建邏輯層,添加一個命令實現創建logic文件和通過參數控制添加默認方法
1、創建命令文件
格式:php artisan make:command 命令文件名
例子:php artisan make:command CreateLogicCommand
這時會在/app/Console/Commands/下生成命令文件
內容如下:
2、注冊命令:/app/Console/Kernel.php中添加一下內容
3、編寫命令
添加命令名稱、參數和描述
創建模板文件logic.stub,和default_method.stub
logic.stub : 邏輯層的主要內容,包含命名空間和類
default_method.stub : 默認方法模板,根據--resource參數來確認是否寫入logic.stub
編寫命令邏輯,主要步驟:
a、獲取參數
b、處理參數,文件和命名空間自動添加Logic后綴
c、獲取模板,替換模板變量,創建文件
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//獲取參數
$args = $this->arguments();
//獲取可選參數
$option = $this->option('resource');
//處理組合參數
$args_name = $args['name'];
if (strstr($args['name'], '/')) {
$ex = explode('/', $args['name']);
$args_name = $ex[count($ex)-1];
$namespace_ext = '/' . substr($args['name'], 0, strrpos($args['name'], '/'));
}
$namespace_ext = $namespace_ext ?? '';
//類名
$class_name = $args_name . 'Logic';
//文件名
$file_name = $class_name . '.php';
//文件地址
$logic_file = app_path() . '/Logic' . $namespace_ext . '/' . $file_name;
//命名空間
$namespace = 'App\Logic' . str_replace('/', '\\', $namespace_ext);
//目錄
$logic_path = dirname($logic_file);
//獲取模板,替換變量
$template = file_get_contents(dirname(__FILE__) . '/stubs/logic.stub');
$default_method = $option ? file_get_contents(dirname(__FILE__) . '/stubs/default_method.stub') : '';
$source = str_replace('{{namespace}}', $namespace, $template);
$source = str_replace('{{class_name}}', $class_name, $source);
$source = str_replace('{{default_method}}', $default_method, $source);
//是否已存在相同文件
if (file_exists($logic_file)) {
$this->error('文件已存在');
exit;
}
//創建
if (file_exists($logic_path) === false) {
if (mkdir($logic_path, 0777, true) === false) {
$this->error('目錄' . $logic_path . '沒有寫入權限');
exit;
}
}
//寫入
if (!file_put_contents($logic_file, $source)) {
$this->error('創建失敗!');
exit;
}
$this->info('創建成功!');
}
4、使用
//如果不需要默認的方法,去掉--reource參數即可
php artisan create:logic Shop/Cart --resource