2017-07-03 81 views
0

所有路由我想從我的模塊打印所有路由「的一些網頁」上的var_dump()或任何調試功能。打印從ZF2模塊

我發現很多帖子和樣品的,但我不能讓他們印在我的代碼最失敗的例子。

到目前爲止,我認爲這是這樣做的最佳方式,但其中使用此代碼?

// $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); 

回答

1

你可以從你的控制器的方法打印的所有路由。請看下面的例子

模塊/應用/ SRC /應用/控制器/ 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構造。我們需要製造這種控制器的工廠。工廠是創建其他類的實例的類。

模塊/應用/ SRC /應用/控制器/ 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關鍵在我們module.config.php

模塊/應用的關鍵controllers /配置/ 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建議!

+0

我會避免使用'$這個 - > getServiceLocator()'作爲自2.7爲廢棄它被標記,不會與Zend框架合作3. 您應該只注入你需要的東西控制器你的控制器。所以考慮使用IndexControllerFactory並將'config ['router']的值注入到IndexController。在https://zendframework.github.io/zend-mvc/migration/to-v2-7/#servicelocatoraware-initializers你可以找到一個例子與工廠 – av3

+0

好控制器,問題是對**的Zend Framework 2 ** :) – unclexo

+0

我知道,但在ZF2中,在控制器中使用'getServiceLocator()'是一種不好的做法。正如我所說的那樣,自2.7以來已經棄用了它,並且爲將來創建新的東西是永不會錯的;)對於您的示例只是一個改進建議。 – av3