laravel 自定義artisan命令,新建repository等類文件


在工作中,有時我們需要定制化一些命令,例如構建repository層,會創建很多的repository文件,如果一一創建,每次都要書寫命名空間太麻煩,可不可以自定義artisan命令呢,像創建Controller文件一樣,省卻書寫固定的代碼,還好laravel給我們提供了這樣自定義的機制.

一 創建命令類

1.創建命令文件
在命令行中輸入下面的命令,會在app\Console目錄下新建Commands\Repository.php文件

php artisan make:command Repository

2.打開Repository.php文件,並添加命令執行的名字

<?php
namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class RepositoryMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *添加命令的名字
     * @var string
     */
    protected $name = 'make:repository';

    /**
     * The console command description.
     *命令的描述
     * @var string
     */
    protected $description = 'Create a new repository class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Repository';

    /**
     * Get the stub file for the generator.
     *執行命令后將創建內容的模板
     * @return string
     */
    protected function getStub()
    {
        return __DIR__.'/stubs/repository.stub';
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
    //注意保存的目錄,我這里把Repository目錄放在了Http下,可以根據自己的習慣自定義
        return $rootNamespace.'\Http\Repositories';
    }
}

二 創建命令類對應的模板

1.創建存放模板文件的目錄stubs
在app\Console\Commands目錄下,新建stubs目錄

2.創建模板文件repository.stub並添加模板
在app\Console\Commands\stubs 目錄下,新建repository.stub文件,並添加以下模板內容

<?php
namespace DummyNamespace;


class DummyClass
{

    /*
    *    將需要使用的Model通過構造函數實例化
    */
    public function __construct ()
    {

    }

}

三 注冊命令類

將創建的RepositoryMakeCommand 添加到app\Console\Kernel.php中

 protected $commands = [
        // 創建生成repository文件的命令
        Commands\RepositoryMakeCommand::class
    ];

四 測試

以上就完成了命令類的自定義,下面就可以使用了

 php artisan make:repository UserRepository

當看到Repository created successfully.的反饋時,就說明我們的配置沒有問題了!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM