雄辩的模型 - 我如何打破这种依赖

时间:2015-02-19 19:33:07

标签: php laravel dependency-injection eloquent laravel-5

采取以下措施:

<?php


class EqUserRepository implements IUserRepository
{
    //...
    public function GetUserByID( $id )
    {
        return User::find( $id );
    }

}

您可以看到它返回User

User正在扩展Model(扩展Eloquent

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    public function Profile()
    {
        return $this->hasOne( "Profile" );
    }

现在想象一下,在我们的控制器中,我们通过接口注入我们的具体实现:

class UserController extends Controller
{
    private $userRepository;

    public function __construct( \App\Models\Contracts\Repositories\IUserRepository $userRepo )
    {
        $this->userRepository = $userRepo;

到目前为止一切都很好!

现在我们有一个控制器方法,它调用我们注入的存储库并获得一个用户返回...

public function GetDetails( $id )
{
        $user = $this->userRepository->GetUserByID( $id );
        return view( 'user', array( "Model" => $user ) );
}

现在我们在视图中呼吁简介:

<p> Name: <?= $Model->Profile()->first_name ?> </p>

哎呀,现在我们的观点依赖于Eloquent,因为Profile上的User方法正在使用Eloquent进行调用。

我一直试图找出打破这种依赖性的最佳解决方案。

  1. 我认为将我的存储库地图数据放入一个没有扩展Eloquent的User类是一个好主意......但是你有一些循环来映射类,这有点浪费时间......特别是考虑到您可以轻松使用mysql_fetch_object( $query, "User" )并立即将其映射。
  2. 因此考虑到1,我认为DB类必须有一种直接映射到类型的方法......
  3. 让用户依赖我的IUserRepository,然后我的Profile函数看起来像这样,这肯定会以一种非常好的方式打破依赖性!
  4. public function Profile()
    {
        return $this->userRepository->GetProfileByUserID( $this->id );
    }
    

    但是你当然不能将DI变成雄辩的模型。我尝试使用引导覆盖方法,但当然也不喜欢DI ......

    所以,提问时间:

    1. 您可以设置数据库类的返回类型吗?
    2. 你能说出一个雄辩的模特DI吗?

0 个答案:

没有答案
相关问题