2017-07-17 74 views
0

我有两种不同的方式来加载我的控制器与它的域模型。我有兴趣听到哪个更好。用于使用域对象填充控制器的zf2工厂

第一种方法 - 传统。 控制器工厂将所需的服务注入到控制器构造函数中。内的控制器的动作,该模型被加载基于所述请求PARAM:

ClientAppointmentsControllerFactory.php

class ClientAppointmentsControllerFactory implements FactoryInterface 
{ 
    public function createService(ServiceLocatorInterface $serviceLocator) {  
     $serviceManager = $serviceLocator->getServiceLocator(); 
     $controller = new ClientAppointmentsController($serviceManager->get('Service\ClientAppointments')); 
     return $controller; 
    } 
} 

ClientAppointmentsController.php

class ClientAppointmentsController extends AbstractActionController 
{ 
    public function __construct(AppointmentFactory $appointmentFactory){ 
     $this->appointmentFactory = $appointmentFactory; 
    } 

    public function indexAction() { 
     $viewModel = $this->acceptableViewModelSelector($this->acceptCriteria); 
     $appointments = $this->appointmentFactory->getClientAppointments($this->params()->fromRoute('clientId')); 
     $viewModel->setVariables([ 
      'appointments' => $appointments 
     ]); 
     return $viewModel; 
    } 
} 

第二方法 - 在工厂访问请求/路由参数 这对我来说似乎有点干净,因为现在控制器不依赖于服务层,只是期望(从任何来源)数组加载的对象传递给视图。我想,这还是符合工厂的定义,因为它是建立与它所需的依赖控制器,虽然目前正积极创建它们,而不是通过这个到控制器做:

ClientAppointmentsControllerFactory.php

class ClientAppointmentsControllerFactory implements FactoryInterface 
{ 
    public function createService(ServiceLocatorInterface $serviceLocator) { 
     $getRequestParam = function($param) use($serviceLocator){ 
      $serviceManager = $serviceLocator->getServiceLocator(); 
      $request = $serviceManager->get('Request'); 
      $router = $serviceManager->get('Router'); 
      $match = $router->match($request); // \Zend\Mvc\Router\RouteMatch 
      $result = $match->getParam($param); 
      return $result; 
     }; 

     $serviceManager = $serviceLocator->getServiceLocator(); 
     $clientService = $serviceManager->get('Service\ClientAppointments'); 
     $appointments = $clientService->fetchByClientId($getRequestParam('clientId)); 
     $controller = new ClientAppointmentsController($appointments); 
     return $controller; 
    } 
} 

ClientAppointmentsController.php

class ClientAppointmentsController extends AbstractActionController 
{ 
    /** 
    * @param Array $appointments Array of Appointment objects 
    */ 
    public function __construct(Array $appointments){ 
     $this->appointments = $appointments 
    } 

    public function indexAction() { 
     $viewModel = $this->acceptableViewModelSelector($this->acceptCriteria); 
     $viewModel->setVariables([ 
      'appointments' => $this->appointments 
     ]); 
     return $viewModel; 
    } 

哪个更好?

(我也有一个可变的工厂漂浮的想法。)

回答

0

IMO,二是都不好,因为它混合创建逻辑与商业逻辑。这意味着业务逻辑错误将阻止工厂工作。

第一个更好,但不好,因为您现在已经掌握了控制器中的业务逻辑。

我会建议将业务逻辑转移到业务模型或控制器插件。