首页 > 技术文章 > laravel创建自定义artisan命令

trblog 2020-04-29 22:06 原文

目的:为了方便的快速创建逻辑层,添加一个命令实现创建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

推荐阅读