【发布时间】:2016-01-22 10:22:48
【问题描述】:
我在将自定义路由添加到我的应用程序时遇到问题。 Zend 框架 1:
我已经在使用默认 Zend 路由的应用程序。我有很多控制器,其中一些我想使用友好的 url,例如: domain.com/cities/edit/id/3 到 domain.com/cities/edit/阿布扎比
有一些控制器可以切换到该网址(以该格式)。
我尝试通过ini文件配置:
resources.router.routes.slugurl.route = /:controller/:action/:slug
也可以通过 Bootstrap 方法:
protected function _initSlugRouter()
{
$this->bootstrap('FrontController');
$router = $this->frontController->getRouter();
$route = new Zend_Controller_Router_Route('/:controller/:action/:slug/',
array(
'controller' => 'slug',
'action' => 'forward',
'slug' => ':slug'
)
);
$router->addRoute('slug',$route);
}
主要问题 - 使用 ini 配置 - 请求直接发送到控制器城市(而不是 slug)。第二个(引导程序) - 也执行城市控制器,但默认路由无法正常工作,我无法执行: domain.com/cities/ 但 domain.com/cities/index/ 有效。未定义操作的错误:
Action "forward" does not exist and was not trapped in __call()
我可以监控控制器中的“slug”/将检查移动到某个库中,但我只想通过路由来执行此操作 - 这种方式对我来说看起来好多了。请问如何解决这个问题?
编辑解决方案摘要 谢谢 Max P. 的有趣。我终于解决了 - 在最后 2 分钟内:) 我在 application.ini 中的路由规则有误。现在定义为:
resources.router.routes.slugurl.route = /:controller/:action/:slug
resources.router.routes.slugurl.defaults.controller = :controller
resources.router.routes.slugurl.defaults.action = :action
resources.router.routes.slugurl.defaults.slug = :slug
控制器是这样定义的:
class CitiesController extends Crm_Abstract
Crm_Abstract 有代码:
<?php
class Crm_Abstract extends Zend_Controller_Action {
public function __construct(\Zend_Controller_Request_Abstract $request, \Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) {
$params = $request->getParams();
if (!empty($params['slug'])) {
$modelSlug = Crm_Helper_Slug::getInstance();
$parameters = $modelSlug->redirectRequest($request);
if ($parameters !== false) {
foreach ($parameters as $key => $value) {
$request->setParam($key, $value);
}
}
}
parent::__construct($request, $response, $invokeArgs);
}
public function __call($methodName, $args) {
parent::__call($methodName, $args);
}
}
slug 助手在定义的控制器处获取 slug 的参数。访问 slug 的 url 被定义/计算来代替 $this->url - 到 $this->slug 并且其余代码在 slug helper 中完成。我不确定我的解决方案是否 100% 确定,因为这是我第一次使用路由。
主要的是——我只需要将 Zend_Controller_Action 更改为扩展 Zend_Controller_Action 的 Crm_Abstract。单行 - 每个控制器中没有额外的自定义代码。
【问题讨论】:
-
如果要评论这条路线 url domain.com/cities/edit/abu-dhabi 会出现什么错误?
-
我会在获得有效错误代码时添加错误 - 我无法在评论中对其进行格式化:(
-
我仍然无法理解 ZF 路由-总是只有一件事无法正常工作-当我添加路由时:
resources.router.routes.slugurl.route = /:controller/:action/:slugresources.router.routes.slugurl.defaults.controller = :controllerresources.router.routes.slugurl.defaults.action = :actionresources.router.routes.slugurl.defaults.slug = :slug我无法访问url:domain.com/developers/ - 错误代码:操作“action”不存在并且没有被困在 __call() 中 - 看起来像是添加了该路由规则 - 破坏了默认路由,但我希望它保留。
标签: zend-framework routing routes router