我正在将我的数据驱动设计重构为领域驱动,我对代码的结构有几个问题
我有一个User entity
namespace Planner\Domain\Entities;
class UserEntity {
private $userId;
private $weight;
private $height;
public function __construct(int $id, float $weight, float $height){
$this->userId = $id;
...
}
}
我还有一个Settings entity应该与用户对象创建一起创建的。
namespace Planner\Domain\Entities;
class SettingsEntity {
private $id;
private $userId;
private $darkTheme;
public function __construct(int $id, int $userId, bool $darkTheme){
$this->id = $id;
$this->userId = $userId;
$this->darkTheme = $darkTheme;
}
}
Settings 对象不能没有 User 存在,因此 settingsEntity 应该由 User 实体管理。这意味着,用户实体不仅仅是一个实体,它应该是一个聚合根。
目前,当用户点击“创建账户”时,App 向 发出 API 请求example.com/user/save,控制器动作将请求对象发送到Planner\Application\Services\UserServicesave 方法。
namespace Planner\Application\Services;
use Planner\Domain\Entities\UserEntity;
use Planner\Domain\Entities\SettingsEntity;
use Planner\Domain\Repositories\UserRepository;
use Planner\Application\Services\SettingsService;
class UserService {
public function __construct(UserRepository $repo, SettingsService $settings){
$this->userRepository = $repo;
$this->settingsService = $settings;
}
public function save($request){
$user = new UserEntity(...);
$settings = new SettingsEntity(...);
if(!$this->userRepository->save($user) || !$this->settingsRepository->save($settings)){
throw new UserCreationFailedException();
}
}
}
问题是,我不知道是否应该一次性创建用户实体和设置实体(从理论上讲,因为我没有用户聚合根,只有一个用户实体)用户聚合根或者当前方式有效。
我还有其他需要同时创建的实体...与设置对象相同,我只是将它们添加到ifUserService 保存方法中的检查中(上面的代码)还是应该全部在用户聚合下,例如:
namespace Planner\Domain;
class User extends AggragateRoot {
public function __construct(UserRepository $repository){
$this->repository = $repository;
}
public function createAccount($request){
$user = new UserEntity(...$request);
$settings = new SettingsEntity(...$user);
$this->repository->save($user, $settings);
}
}
MYYA
温温酱