你可以從你的控制器的方法打印的所有路由。請看下面的例子
模塊/應用/ 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建議!
我會避免使用'$這個 - > getServiceLocator()'作爲自2.7爲廢棄它被標記,不會與Zend框架合作3. 您應該只注入你需要的東西控制器你的控制器。所以考慮使用IndexControllerFactory並將'config ['router']的值注入到IndexController。在https://zendframework.github.io/zend-mvc/migration/to-v2-7/#servicelocatoraware-initializers你可以找到一個例子與工廠 – av3
好控制器,問題是對**的Zend Framework 2 ** :) – unclexo
我知道,但在ZF2中,在控制器中使用'getServiceLocator()'是一種不好的做法。正如我所說的那樣,自2.7以來已經棄用了它,並且爲將來創建新的東西是永不會錯的;)對於您的示例只是一個改進建議。 – av3