源碼解讀[ GeneratorCommand ],創(chuàng)建文件命令

熟練使用 artisan 命令如 php artisan make:model 等來創(chuàng)建文件的 laravel 盆友們,肯定不習(xí)慣點(diǎn)擊右鍵新建文件,尤其是大量重復(fù)這樣的操作真的很繁瑣有沒有!

所以想著折騰自定義一條 artisan 命令,實(shí)現(xiàn)新建文件功能。網(wǎng)上查了查,發(fā)現(xiàn) laravel 已經(jīng)把輪子造好了,只要繼承基類 GeneratorCommand,便可簡單實(shí)現(xiàn)功能。題外話:習(xí)慣不好,很多時(shí)候?qū)幵?Google 教程做伸手黨,也不愿意帶著問題通讀代碼。在此共勉!

源碼解讀

 public function fire()
    {
        //獲取拼接命名空間后的全稱
        $name = $this->qualifyClass($this->getNameInput());

        //獲取文件的實(shí)際存儲(chǔ)路徑
        $path = $this->getPath($name);

        //若文件已存在,直接給出錯(cuò)誤提示而不會(huì)覆蓋原來的文件
        if ($this->alreadyExists($this->getNameInput())) {
            $this->error($this->type.' already exists!');
            return false;
        }

        //生成文件
        $this->makeDirectory($path);

        //適當(dāng)?shù)靥鎿Q模版文件中的數(shù)據(jù),如命名空間和類名
        $this->files->put($path, $this->buildClass($name));

       //控制臺(tái)提示
        $this->info($this->type.' created successfully.');
    }

由上述代碼可以看出,輪子已經(jīng)造的很完備了。其他部分都比較簡單,具體看下模版文件替換部分的代碼,從而按需求編輯模版文件。

*編輯模版文件

protected function buildClass($name)
    {
        //獲取模版文件
        $stub = $this->files->get($this->getStub());
        //替換命名空間和類名
        return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name);
    }

*DummyNamespace=命名空間

 protected function replaceNamespace(&$stub, $name)
    {
        $stub = str_replace(
            ['DummyNamespace', 'DummyRootNamespace'],
            [$this->getNamespace($name), $this->rootNamespace()],
            $stub
        );

        return $this;
    }

根據(jù)自定義的命名空間替換模版文件中的命名空間,所以模版文件中的命名空間用 DummyNamespace 來代替。這點(diǎn)在讀源碼之前看 migrate 的 create.stub 代碼時(shí),真心一臉懵逼啊。

*DummyClass=類名

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

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

同理可得,模版文件中的類名用 DummyClass 代替。

實(shí)現(xiàn)

很明確分成兩步:

  1. 創(chuàng)建模版文件 xxx.stub
  2. 創(chuàng)建命令——生成文件

*模版

簡單例子 public/stubs/repo.stub,可根據(jù)需要添加構(gòu)造函數(shù)等共性代碼:

<?php

namespace DummyNamespace;

class DummyClass
{

}

*command 命令

class MakeRepo extends GeneratorCommand
{
    //執(zhí)行命令
    protected $signature = 'make:repo {name}';

   //命令說明
    protected $description = 'Create a new repo';

   //模版文件存儲(chǔ)路徑
    public function getStub()
    {
        return public_path('stub/repo.stub');
    }

    //為生成文件指定命名空間
    public function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Repos';
    }
}

看起來有沒有很簡單,若對(duì) artisan 命令不熟的小伙伴先移步 artisan 命令行看看文檔了解下。希望能養(yǎng)成記筆記的好習(xí)慣,供以后自己閱讀吧。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容