为什么在 Laravel 中,有些用 Repositories 而不是 Model?
本人是从lv5.0开始学习的,对lv4.x的不了解。
在看别人的项目的时候,常常看到别人使用repo这种方式来操作数据库。使用repo,除了model之外,要先定义一些interface, 现在再implement 这些interface。 代码绕来绕去没有看懂。
问为什么要使用repositor partern 这种方式呢?我可以在model里面定义方法啊。下面我写的一个model.
要获取数据,我可以直接 Tag->Domains()或 Tag::getDomainId('hello') 这种啊。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class Tag extends Model
{
protected $table = "tags";
protected $fillable = ['user_id', 'name', 'slug', 'counter', 'deleted'];
public function removeTagDomain() {
DB::table('domaintag')->where (['tag_id'=> $this->id])->delete();
}
public function domains () {
return DB::table('domaintag')
->where (['tag_id'=> $this->id])
->join("domains", "domains.id", "=", "domaintag.domain_id")
->select('domains.name')
->orderBy('domains.name')
->get();
}
public static function getDomainId($name) {
$slug = str_replace(' ', '-', trim(strtolower($name)));
return DB::table ('tags')->where('slug', $slug)
->join ('domaintag', 'domaintag.tag_id', '=', 'tags.id')
->select ('domaintag.domain_id')->get();
}
}
推荐文章: