采取以下措施:
<?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进行调用。
我一直试图找出打破这种依赖性的最佳解决方案。
mysql_fetch_object( $query, "User" )
并立即将其映射。DB
类必须有一种直接映射到类型的方法...... IUserRepository
,然后我的Profile
函数看起来像这样,这肯定会以一种非常好的方式打破依赖性!
public function Profile()
{
return $this->userRepository->GetProfileByUserID( $this->id );
}
但是你当然不能将DI变成雄辩的模型。我尝试使用引导覆盖方法,但当然也不喜欢DI ......
所以,提问时间: