面向服务架构(SOA) MVC - 我应该在哪里填充实体的属性?

发布于 2024-12-28 05:54:28 字数 975 浏览 3 评论 0原文

我正在开发一个大量使用服务的 MVC 应用程序。我的问题是,创建实体时,我应该从控制器内还是从服务内填充其属性?

示例 1 - 从控制器内部填充:

// MyController.php
function someAction() {
  $name = $_POST['name'];
  $gender = $_POST['gender'];

  $user = new User();
  $user->setName($name);
  $user->setGender($gender);

  $userService->createUser($user);
}

// UserService.php
function createUser($user) {
  $this->saveToDb($user);
}

示例 2 - 从服务内部填充:

// MyController.php
function someAction() {
  $name = $_POST['name'];
  $gender = $_POST['gender'];

  $userService->createUser($name, $gender);
}

// UserService.php
function createUser($name, $gender) {
  $user = new User();
  $user->setName($name);
  $user->setGender($gender);

  $this->saveToDb($user);
}

我更喜欢第二种方法,因为我觉得控制器应该简单地委托工作,而服务层应该承担繁重的工作。

它似乎也遵循 DRY 原则,因为如果我有多个需要创建 User 对象的控制器,我将不会重复任何代码。编写单元测试也是如此 - 我可以简单地将所有参数传递给服务对象。

但我也看到了第一种方法的使用,我想知道它是否有一些我没有看到的优点。

I'm working on an MVC app that makes heavy use of Services. My question is, when creating an entity, should I populate its properties from within the controller, or from within a service?

Example 1 - Populating from within controller:

// MyController.php
function someAction() {
  $name = $_POST['name'];
  $gender = $_POST['gender'];

  $user = new User();
  $user->setName($name);
  $user->setGender($gender);

  $userService->createUser($user);
}

// UserService.php
function createUser($user) {
  $this->saveToDb($user);
}

Example 2 - Populating from within service:

// MyController.php
function someAction() {
  $name = $_POST['name'];
  $gender = $_POST['gender'];

  $userService->createUser($name, $gender);
}

// UserService.php
function createUser($name, $gender) {
  $user = new User();
  $user->setName($name);
  $user->setGender($gender);

  $this->saveToDb($user);
}

I like the 2nd approach better, because I feel the controller should simply delegate work out, and the service layer should do the heavy lifting.

It also seems to follow the DRY principle because if I have multiple controllers that need to create User objects, I won't be repeating any code. The same goes for writing unit tests - I can simply pass all the arguments to the service object.

But I've seen the first method used as well, and I'm wondering if there's some advantage to it that I'm not seeing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回心转意 2025-01-04 05:54:28

我会选择第二种方法,因为它是 DRY 的。

第一种方法是可以的,但是您应该传递 DTO,而不是数据库实体,您可以使用它来填充服务内的数据库实体。我不会从服务中公开数据库实体,以便将数据库层与表示层分离。

I would go with the second approach, as it is DRY.

The first approach is ok, but instead of DB entity you should be passing DTO, which you can use to populate your DB entity inside the service. I would not expose DB entities from the service, in order to decouple DB layer from presentation layer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文