[英]Print all routes from ZF2 modules
我正在尝试使用var_dump()或任何调试功能在“某些页面”上打印模块中的所有路由。
我发现了很多帖子和示例,但是我无法打印它们,并且大多数示例在我的代码中都失败了。
到目前为止,我认为这是最好的方法,但是在哪里可以使用此代码?
// $sl instanceof Zend\ServiceManager\ServiceManager
$config = $sl->get('Config');
$routes = $config['router']['routes'];
如果要仅出于调试目的查看所有路由,则可以在路由器对象上使用var_dump或类似的路由:
// $sl instanceof Zend\ServiceManager\ServiceManager
$router = $sl->get('Router');
var_dump($router);
您可以从控制器的方法中打印所有路线。 看下面的例子
模块/应用程序/源代码/应用程序/控制器/IndexController.php
<?php
namespace Application\Controller;
use Zend\View\Model\ViewModel;
use Zend\Mvc\Controller\AbstractActionController;
class IndexController extends AbstractActionController
{
/**
* @var array
*/
protected $routes;
/**
* @param array $routes
*/
public function __construct(array $routes)
{
// Here is the catch
$this->routes = $routes;
}
public function indexAction()
{
// Thus you may print all routes
$routes = $this->routes;
echo '<pre>';
print_r($routes);
echo '</pre>';
exit;
return new ViewModel();
}
}
当我们将路由数组传递给IndexController
的构造函数时。 我们需要为此控制器制造工厂。 工厂是创建其他类的实例的类。
模块/应用程序/源代码/应用程序/控制器/IndexControllerFactory.php
<?php
namespace Application\Controller;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class IndexControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$serviceManager = $serviceLocator->getServiceLocator();
$config = $serviceManager->get('Config');
$routes = $config['router'];
return new IndexController($routes);
}
}
不能使用参数构造可调用类。 我们的控制器无法作为invokables
因为我们知道我们已经将参数传递给了它的构造函数。 因此,我们需要配置在factories
键下controllers
我们的关键module.config.php
module / Application / config / module.config.php
'controllers' => [
'invokables' => [
// This would not work any more as we created a factory of it
// 'Application\Controller\Index' => 'Application\Controller\IndexController',
],
// We should do it thus
'factories' => [
'Application\Controller\Index' => 'Application\Controller\IndexControllerFactory',
],
],
已按照@ av3的建议对此答案进行了良好实践的编辑!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.