在ZF2中我们在module.config.php中配置路由,如下所示:
'router' => array(
'routes' => array(
'admin' => array(
'type' => 'segment',
'options' => array(
'route' => '/admin[/:action][/:id][/:page]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9a-zA-Z]+',
'page' => 'page\-[a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Admin\Controller\Admin',
'action' => 'index',
),
),
),
),
),
是否可以在视图助手或控制器中访问此数组的元素?如果它是如何实现的呢?
答案 0 :(得分:3)
在您的控制器中,您可以从服务定位器获取它:
$serviceLocator = $this->getServiceLocator();
$config = $serviceLocator->get("config");
$router = $config["router"];
要从视图中访问它,您可以像这样创建一个View Helper:
1. ConfigHelper 类:
use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
//IT NEEDS TO IMPLEMENT ServiceLocatorAwareInterface IN ORDER TO USE THE ServiceLocator
class ConfigHelper extends AbstractHelper implements ServiceLocatorAwareInterface
{
private $config, $helperPluginManager, $serviceManager;
public function getConfig() {
if ( !isset( $this->config ) ) {
$this->config = $this->serviceManager->get( 'config' );
}
return $this->config;
}
/**
* Set the service locator.
*
* @param ServiceLocatorInterface $serviceLocator
* @return CustomHelper
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
$this->serviceLocator = $serviceLocator;
return $this;
}
/**
* Get the service locator.
*
* @return \Zend\ServiceManager\ServiceLocatorInterface
*/
public function getServiceLocator() {
return $this->serviceLocator;
}
public function __invoke() {
if ( !isset( $this->helperPluginManager ) || !isset( $this->serviceManager ) ) {
$this->helperPluginManager = $this->getServiceLocator();
//USING THE ServiceLocator YOU CAN GET THE serviceManager NEEDED TO GET THE CONFIG ARRAY
$this->serviceManager = $this->helperPluginManager->getServiceLocator();
}
return $this;
}
}
2. 模块类:
public function getViewHelperConfig()
{
return array(
'invokables' => array(
'confighelper' => '<NAMESPACE>\ConfigHelper',
),
);
}
3. 查看模板:
$config = $this->configHelper()->getConfig();
$router = $config["router"];