如何将不同的 Eloquent 模型注入到特征方法中?
How can I inject different Eloquent Models into the method of a trait?
我希望在我的 Laravel 5 应用程序中跨控制器保持 DRY。我选择的路线是使用 Trait 和我可以应用于我的单独控制器的方法。
我的 Trait 中的方法需要作用于不同的模型 类。它们始终是 Eloquent 模型 的子类。
这是我的尝试:
<?php namespace Conjunto\Traits;
use Illuminate\Database\Eloquent\Model;
trait SortableTrait
{
/**
*
*/
public function upPosition(Model $model)
{
dd($model);
}
}
我很遗憾收到以下错误,因为 Eloquent 模型本身不可实例化:
Target [Illuminate\Database\Eloquent\Model] is not instantiable.
我怎样才能使这个具有特征的工作?
解决方案是在构造函数中注入具体模型,将其设置为 属性 并在 Trait 的 upPosition 方法中使用此 属性。
controller UserController
{
protected $model;
use SortableTrait;
public function __construct(User $user)
{
$this->model = $user;
}
}
现在在你的 Trait 中,你应该将你的方法更改为:
public function upPosition()
{
dd($this->model);
}
我希望在我的 Laravel 5 应用程序中跨控制器保持 DRY。我选择的路线是使用 Trait 和我可以应用于我的单独控制器的方法。
我的 Trait 中的方法需要作用于不同的模型 类。它们始终是 Eloquent 模型 的子类。
这是我的尝试:
<?php namespace Conjunto\Traits;
use Illuminate\Database\Eloquent\Model;
trait SortableTrait
{
/**
*
*/
public function upPosition(Model $model)
{
dd($model);
}
}
我很遗憾收到以下错误,因为 Eloquent 模型本身不可实例化:
Target [Illuminate\Database\Eloquent\Model] is not instantiable.
我怎样才能使这个具有特征的工作?
解决方案是在构造函数中注入具体模型,将其设置为 属性 并在 Trait 的 upPosition 方法中使用此 属性。
controller UserController
{
protected $model;
use SortableTrait;
public function __construct(User $user)
{
$this->model = $user;
}
}
现在在你的 Trait 中,你应该将你的方法更改为:
public function upPosition()
{
dd($this->model);
}