有没有人使用IoC容器绑定到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(); } }
解决方法
虽然你可以这样做,但你可能不想这样做.如果您这样做,IoC容器将始终使用该绑定来解析帐户,这不是您正在寻找的.
更合适的方法是为如何解析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); });