コントローラにドメインモデルをロードする2つの異なる方法があります。私はより良い聴覚に興味があるでしょう。zf2コントローラにドメインオブジェクトを設定するためのファクトリ
最初の方法 - 伝統的です。 コントローラファクトリは、コントローラコンストラクタに必要なサービスを注入します。 - 工場で要求/ルートパラメータにアクセス
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;
}
}
第2の方法:コントローラのアクション、モデルが要求PARAMに基づいてロードされ、内 これはコントローラがサービス層に依存しないようになり、(何らかのソースから)配列を期待するようになりました。ロードされたオブジェクトをビューに渡す今積極的にそれらを作成する代わりに行うために、コントローラ上にこれを渡しているが、私は、それはそれが必要なの依存関係を持つコントローラを作成しているので、これはまだ、工場の定義に合うと思う:
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;
}
?
(私も漂っ可変工場のアイデアを持っている。)