【发布时间】:2013-11-25 15:20:30
【问题描述】:
阅读许多有关 Laravel 4 的书籍,它是通过 IoC 容器使用接口和实现的结构。 所以现在所有这些信息我什么都不懂。
例如我有这样的结构:
app
-- config
-- database
-- lang
-- ...
-- logic
-- -- MyAPP
-- -- -- Controllers
-- -- -- Interfaces
-- -- -- Libraries
-- -- -- Models
-- -- -- -- User
-- -- -- -- -- Profile.php
-- -- -- -- -- User.php
-- -- -- Repositories
-- -- -- ServiceProviders
我有 User 模型和 Profile 模型,没有 User 模型就不能存在,因为它是一对一的关系。
例如我有用户界面:
interface UserInterface
{
public function find($userId);
public function findProfile($userId);
public function replace($userId, $attributes, $profileAttributes);
}
实现如下:
class UserRepository implements UserInterface
{
protected $user;
protected $profile;
public function __construct(Model $user, Model $profile)
{
$this->user = $user;
$this->profile = $profile;
}
public function find($userId)
{
return $this->user->find($userId);
}
public function findProfile($userId)
{
return $this->profile->where('user_id', $userId)->first();
}
public function replace($userId, $attributes, $profileAttributes)
{
//
}
}
所以我的问题是,如果我尝试实现 UserRepository 注入两个模型 User 和 Profile 的 SOLID 原则,这是一种很好的做法,或者创建 ProfileInterface 并将其注入 UserRepository 是正确的方法,所以会有这样的事情:
public function __construct(Model $user, ProfileInterface $profile)
我无法理解的是,组织依赖项的正确方法是什么。因为我认为 ProfileInterface 应该具有所有 Profile 功能,但另一方面它不能没有用户存在,因为我们首先在表中创建用户,然后在第二个 user_profiles 表中添加它的详细信息。
在哪里存储功能会更好。用户和他的 UserProfile 功能在一个界面 - UserInterface 或单独的界面中: UserInterface 和 ProfileInterface 注入 UserInterface ?
如果 ProfileInterface 被注入到 UserInterface 我应该如何创建新用户(使用 Eloquent)?
【问题讨论】:
-
您是否会在不加载用户个人资料的情况下加载用户?
-
不,我将始终访问 $user,并将通过这样的关系访问他的个人资料; $user->profile->some_profile_field,其中profile是指向Profile模型的关系方法