php – 将Eloquent模型绑定到服务容器

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...