# 如何自行建立 php artisan make: 模板 PART(1) >製作:Tinn >參考:Google各位大神、laravel官網... --- 在laravel中要建立一個Controller很簡單,但若是要建立 Services、Repository甚至是自己的模板該如何做了!! 以下就開始動手做吧 :muscle: --- ## 目標? - [php aritisan make:repository](https://hackmd.io/X1z5ahqDQli6PbVf8IOLFw?both) - php aritisan make:services - php aritisan make:autoclass (一次性創建controller、repository、services) --- ### 生成文件 在app\Console\Commands資料夾下建立RepositoryMakeCommand.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) { return $rootNamespace.'\Repositories'; } } ``` --- ### 建立模版檔案 在app\Console\Commands\stubs下建立模版檔案 .stub檔案是make命令生成的類檔案的模版,用來定義要生成的類檔案的通用部分建立repository.stub模版檔案: 我的範例檔如下: --- ```php= namespace App\Repository; use DB; use Illuminate\Database\QueryException; class DummyClass extends DefaultRepository { public function __construct() { //DB::connection()->enableQueryLog(); //開啟sql 查詢紀錄 $this->_unixTime = time(); $this->_now = date('Y-m-d H:i:s'); $this->_table = ''; } /**範例 * @param $exampleId * @return bool */ public function example($exampleId, $employeeId) { try { return DB::table($this->_table) ->where('exampleId', '=', $exampleId) ->first(); } catch (QueryException $e) { $this->addSqlErrorLog($e->getCode(), $this->_table, $e->getMessage(), $employeeId); return false; } } } ``` --- ### 註冊命令類 --- 將RepositoryMakeCommand新增到App\Console\Kernel.php中 --- ```php= protected $commands = [ Commands\RepositoryMakeCommand::class ]; ``` --- # 好了完成可以開始食用 :fork_and_knife: --- ### Thank you! :sheep: ###### tags: `laravel`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up