douzheng0702 2017-02-15 15:19
浏览 32

一个控制器和许多服务的设计模式

I'm currently facing problem with correct design patterns for following problem in MVC:

I have following classes:

GroupController   
GroupService 
GroupUserController  
GroupUserService   
LogService

(One Group may have many users)

For each controller I have CRUD, which is available for user's with certain role.
One of the functionality is that logged user may create group (GroupService). If he does that, then he must be assigned automatically to user group (GroupUserService). I also need to log information to LogService when and how (by CRUD or by method available only for specific role) user created group.

Currently I have something like this:

// GroupController.php
// Create new group
public function setAction()
{
    //code...

    if ($this->getRequest()->isPost()) {
        $data = $this->request->getPost()->toArray();
        $form->setData($data);

        if ($form->isValid()) {
            $data = $form->getData();
            $result = $groupService->save($data, $data['id']);

            // Add user to that group
            if ($result) {
                $groupUserData = [
                    'group' => $result->getId(),
                    'user' => $user->getId()
                ];
                $result2 = $groupUserService->save($groupUserData); // <---- service which shouldn't be here?

                if ($result2) {
                    // Some other action let's say with another service
                }

                $logData = [
                    'msg' => 'New Group created!',
                    'created_at' => new \DateTime()
                ];
                $logService->save($logData); // <---- this service shouldn't be also here?
            }

            $this->redirect()->toRoute($this->route);
        }
    }

    return $this->viewModel;
}

For now, this action is doing many tasks instead of just one. Isn't that breaking of SOLID principle?
I think these services shouldn't be in this controller.

What design patterns should I use here? Chain of Responsibility? Observer? Mediator?

Such problem I have in many controllers. I mean many actions need use of multiple services

  • 写回答

2条回答 默认 最新

  • doulangchao8934 2017-02-16 11:02
    关注

    I think you can use a facade pattern, Which aims to encapsulate/hide the complexity of certain procedures.

    so you can create a class contains a method that's hold all your action logic. and simply call it from the action.

    Just one point regarding to your status I think you may also need a transaction to wrap your queries.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog