在 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',
),
),
),
),
),
是否可以在 View 助手或 Controller 中访问此数组的元素?如果是怎么实现呢?
最佳答案
在您的 Controller 中,您可以从服务定位器获取它:
$serviceLocator = $this->getServiceLocator();
$config = $serviceLocator->get("config");
$router = $config["router"];
要从 View 访问它,您可以创建一个 View 助手,如下所示:
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"];
关于php - ZF2 - 获取路由器配置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24840451/