脚本宝典收集整理的这篇文章主要介绍了php – 将Eloquent模型绑定到服务容器,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
例如,我有一个我的帐户和类别雄辩模型的存储库. Account模型与Categories具有hasmany关系.类别存储库将Account存储库注入构造函数.
在我的服务提供商中:
$this->app->bind(App\Models\Account::class,function ($app) { return (Auth::check()) ? Auth::user()->account : null; });
在我的存储库中
use App\Models\Account; class CategoryReposITory { PRivate $account; public function __construct(Account $account = null) { // check and throw error if null $this->account = $account; } public function getAll() { return $this->account->categories()->get(); } }
更合适的方法是为如何解析CategoryRepository而不是Account定义绑定.这样,在解析CategoryRepository的代码中,您可以确保始终传入实际帐户,如果不可用则确保为null.
$this->app->bind(App\Repos\CategoryRepository::class,function ($app) { $account = Auth::check() ? Auth::user()->account : null; return new App\Repos\CategoryRepository($account); });
以上是脚本宝典为你收集整理的php – 将Eloquent模型绑定到服务容器全部内容,希望文章能够帮你解决php – 将Eloquent模型绑定到服务容器所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。