laravel
框架可以通过php artisan make:model
快速的创建自己的model
,可以节省我们大量的宝贵时间
那么有没有办法重写这个命令,因为我们想自定义model
的内容,更适合我们的编码习惯
将常用的代码都写在model
里
以下代码可以实现
app/Console/Commands/makeModel.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class makeModel extends GeneratorCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
//protected $signature = 'make:controller {name : 名称}';
protected $name = 'make:model';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Model description';
/**
* Create a new command instance.
*
* @return void
*/
protected $type = 'Model'; // command type
protected function getStub() {
return __DIR__ . '/stubs/Model.stub';
}
protected function getDefaultNamespace($rootNamespace) {
return $rootNamespace . '\Models';
}
}
//https://blog.csdn.net/yageeart/article/details/85875470
以下是model
的模板文件
app/Console/Commands/stubs/model.stub
<?php
namespace DummyNamespace;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class DummyClass extends Model
{
//
protected $connection = 'mysql';
protected $table = 'DummyClass';
public $timestamps = true;
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
protected $guarded = [];
protected $fillable = [];
use SoftDeletes;
//作用域
public function scopeValid($query){
return $query->where('is_valid', 1);
}
public function scopeType($query, $type){
return $query->where('is_valid', $type);
}
//定义访问器
public function getNameAttribute($value){
return ucfirst($value);
}
//定义修改器
public function setNameAttribute($value){
$this->attributes['name'] = strtolower($value);
}
public function phone(){
return $this->hasOne("App\Phone");
}
public function comment(){
return $this->hasMany("App\Comment");
}
}
执行命令php artisan make:model Test/ApiModel
我们可以在app/Models/Test
中找到ApiModel.php
<?php
namespace App\Models\Test;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ApiModel extends Model
{
//
protected $connection = 'mysql';
protected $table = 'ApiModel';
public $timestamps = true;
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
protected $guarded = [];
protected $fillable = [];
use SoftDeletes;
//作用域
public function scopeValid($query){
return $query->where('is_valid', 1);
}
public function scopeType($query, $type){
return $query->where('is_valid', $type);
}
//定义访问器
public function getNameAttribute($value){
return ucfirst($value);
}
//定义修改器
public function setNameAttribute($value){
$this->attributes['name'] = strtolower($value);
}
public function phone(){
return $this->hasOne("App\Phone");
}
public function comment(){
return $this->hasMany("App\Comment");
}
}
我们也可以将模板改为更符合自己的编码
如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术
转载请注明:laravel框架自定义make:model命令 出自老鄢博客 | 欢迎分享