zf2工厂用于使用域对象填充控制器

时间:2017-07-17 14:56:18

标签: zend-framework2

我有两种不同的方法可以使用它的域模型加载我的控制器。我有兴趣听听哪个更好。

第一种方法 - 传统方法。 控制器工厂将所需的服务注入控制器构造函数。在控制器操作中,模型基于请求参数加载:

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;
    }

哪个更好?

(我也知道一个可变的工厂漂浮在周围。)

1 个答案:

答案 0 :(得分:0)

IMO,第二个并不擅长,因为它将创建逻辑与业务逻辑混合在一起。这意味着业务逻辑错误将阻止工厂工作。

第一个更好,但不好,因为你现在在控制器中有了业务逻辑。

我建议将业务逻辑转换为业务模型或控制器插件。