有沒有人使用IoC容器綁定到Eloquent模型?
例如,我有一個我的帳戶和類別雄辯模型的存儲庫. Account模型與Categories具有hasMany關系.類別存儲庫將Account存儲庫注入構造函數.
相反,我想注入一個像這樣的實際賬戶模型……
vue 依賴注入。在我的服務提供商中:
$this->app->bind(App\Models\Account::class, function ($app) {
return (Auth::check()) ? Auth::user()->account : null;
});
php模型是什么,在我的存儲庫中
use App\Models\Account;
class CategoryRepository
{
php用什么容器。private $account;
public function __construct(Account $account = null)
{
// check and throw error if null
php容器概念?$this->account = $account;
}
public function getAll()
{
Orm模型php?return $this->account->categories()->get();
}
}
如果我將一個實際的雄辯模型綁定到構造函數中,那么這是不好的做法,還是我會陷入可預見的陷阱?
php創建數據庫和表。最佳答案 雖然你可以這樣做,但你可能不想這樣做.如果您這樣做,IoC容器將始終使用該綁定來解析帳戶,這不是您正在尋找的.
更合適的方法是為如何解析CategoryRepository而不是Account定義綁定.這樣,在解析CategoryRepository的代碼中,您可以確保始終傳入實際帳戶,如果不可用則確保為null.
$this->app->bind(App\Repos\CategoryRepository::class, function ($app) {
$account = Auth::check() ? Auth::user()->account : null;
php進程模型?return new App\Repos\CategoryRepository($account);
});
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态