laravel自定义命令新建类模板文件

在使用laravel的时候,都会用到诸如,make:controller,make:auth等等内置的命令,的确很方便。我们也可以自定义类似的命令,使用模板,从而简化开发过程。

自定义非常简单,只需要做两步:

  1. 创建命令入口。
  2. 定义模板,stub后缀文件。

1.创建命令入口:

<?php
/**
 * =======================================
 * @Author : haibo
 * @Time   : 18-9-17-上午9:26
 * @File   : OrderTypeMakeCommand.php
 * =======================================
 */


namespace App\Console\Commands;


use Illuminate\Console\GeneratorCommand;


class OrderTypeMakeCommand extends GeneratorCommand
{
    
    protected $name = "make:ordertype";

    protected $description = "Create new order type SQL for finance ";

    protected $type = "DataSQLAbstract";

    /**
     *
     *
     * 模板文件位置。
     *
     * 如果是下面的,stub文件是在app\Console\Commands目录下。
     *
     * @return string
     *
     *
     */
    protected function getStub()
    {
        return __DIR__."/stubs/ordertype.stub";
    }


    /**
     * @param string $rootNamespace
     *
     *
     *获取命名空间,根命名空间是app.这里要根据实际情况自定义自己的命名空间。注意反斜杠。
     *
     * @return string
     *
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace."\DataSQL\SumDaily";
    }


}

2.创建模板

app/console/commands/stub/ordertype.stub

<?php

namespace DummyNamespace;

use APP\DataSQL\DataSQLAbstract;

class DummyClass extends DataSQLAbstract
{

    public function reprClass()
    {
       return "SuMDaily SQL Factory::create different sqls about sap sum daily";
    }

    public function getNormalSQL()
    {

    }


}

上面的DummyNameSpace和DummyClass很重要。定义了这两个,最终创建类文件时才会替换成相应的名称。

具体实现是在命令入口继承的父类:GeneratorCommand.

  protected function replaceNamespace(&$stub, $name)
    {
        $stub = str_replace(
            ['DummyNamespace', 'DummyRootNamespace', 'NamespacedDummyUserModel'],
            [$this->getNamespace($name), $this->rootNamespace(), config('auth.providers.users.model')],
            $stub
        );

        return $this;
    }


 protected function replaceClass($stub, $name)
    {
        $class = str_replace($this->getNamespace($name).'\\', '', $name);

        return str_replace('DummyClass', $class, $stub);
    }

--------EOF---------
微信分享/微信扫码阅读