你可以使用控制器插件。
像這樣,您可以在需要時在控制器內部獲得適配器,而無需注入ServiceManager
,也無需向工廠添加所有邏輯。只有在您的控制器操作方法中請求適配器時,該適配器纔會被實例化。
首先,你需要創建(延長Zend\Mvc\Controller\Plugin\AbstractPlugin
)控制器插件類:
<?php
namespace Application\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
class AdapterPlugin extends AbstractPlugin{
protected $adapterProviderService;
public function __constuct(AdapterProviderService $adapterProviderService){
$this->adapterProviderService = $adapterProviderService;
}
public function getAdapter($param){
// get the adapter using the param passed from controller
}
}
然後工廠在類中注入你的服務:
<?php
namespace Application\Controller\Plugin\Factory;
use Application\Controller\Plugin\AdapterPlugin;
class AdapterPluginFactory implements FactoryInterface
{
/**
* @param ServiceLocatorInterface $serviceController
* @return AdapterPlugin
*/
public function createService(ServiceLocatorInterface $serviceController)
{
$serviceManager = $serviceController->getServiceLocator();
$adapterProvicerService = $serviceManager>get('Application\Service\AdapterProviderService');
return new AdapterPlugin($adapterProviderService);
}
}
然後,你需要註冊你的插件在你的module.config.php
:
<?php
return array(
//...
'controller_plugins' => array(
'factories' => array(
'AdapterPlugin' => 'Application\Controller\Plugin\Factory\AdapterPluginFactory',
)
),
// ...
);
現在你可以使用這裏面你的控制器動作是這樣的:
protected function controllerAction(){
$plugin = $this->plugin('AdapterPlugin');
// Get the param for getting the correct adapter
$param = $this->getParamForAdapter();
// now you can get the adapter using the plugin
$plugin->getAdapter($param);
}
瞭解更多關於控制器插件here in the documentation
我想你能夠訪問你的工廠使用SM請求對象。因此,在注入對控制器的依賴之前,只需抓住它並獲取參數並檢查條件。如果兩個適配器都屬於通用接口,則需要定義映射器接口。 –
不幸的是,情況並非如此。似乎,在Apigility中,只有在調用操作後才能使用過濾參數,而不是在構造函數中。我已經測試過這個作爲第一個選項:) – Ivan