vue 依賴注入,php注冊 綁定的容器,php – 將Eloquent模型綁定到服務容器

 2023-10-20 阅读 19 评论 0

摘要:有沒有人使用IoC容器綁定到Eloquent模型?例如,我有一個我的帳戶和類別雄辯模型的存儲庫. Account模型與Categories具有hasMany關系.類別存儲庫將Account存儲庫注入構造函數.相反,我想注入一個像這樣的實際賬戶模型……vue 依賴注入。在我的服務提供商中:$this-&

有沒有人使用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);

});

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/152382.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息