Skip to content

自定义指令

liaofei edited this page Jan 20, 2021 · 1 revision

自定义命令

根目录配置文件configconsole.php中添加

return [
    // 指令定义
    'commands' => [
        'make:service'=>\crmeb\command\Service::class,
    ],
];

目录crmeb\command\下定义命令实现类,比如实现自动创建一个services类:

<?php

namespace crmeb\command;

use think\console\command\Make;

/**
 * Class Service 
 * @package crmeb\command
 */
class Service extends Make
{
    protected $type = "Dao";

    protected function configure()
    {
        parent::configure();
        $this->setName('make:service')
            ->setDescription('Create a new service class');
    }

    protected function getStub(): string
    {
        return __DIR__ . DIRECTORY_SEPARATOR. 'stubs' . DIRECTORY_SEPARATOR . 'service.stub';
    }

    protected function getNamespace(string $app): string
    {
        return parent::getNamespace($app) . '\\services';
    }

    protected function getPathName(string $name): string
    {
        $name = str_replace('app\\', '', $name);

        return $this->app->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . 'Services.php';
    }
}

\crmeb\command\stubs,创建service.stub文件,定义创建services文件模版:

<?php

declare (strict_types = 1);

namespace {%namespace%};

use app\dao\BaseDao;
use app\model\***\{%className%};

/**
 *
 * Class {%className%}Dao
 * @package {%namespace%}
 */
class {%className%}Dao extends BaseDao
{

    /**
     * 设置模型
     * @return string
     */
    protected function setModel(): string
    {
        return {%className%}::class;
    }

}

在项目根目录打开命令行,执行命令

php think -help

查看刚才创建的命令是否在其中:

执行创建命令

php think make:service cs/Test

执行成功如图: 查看目录结构,文件已经创建:

Clone this wiki locally