更改 Zend URL 中的分隔字符
-
12-12-2019 - |
题
使用 Zend Framework 和视图的 url 方法:
$this->url(array('field1' => this, 'field2' => 'is', 'field3' => 'my example'), 'route_name');
其中,route_name 是 url 路由的名称,每个字段# 都是从数据库中检索的。
我注意到默认情况下它将控制器/操作名称中的空格更改为加号,如下所示:
www.example.com/this is my example
到
www.example.com/this+is+my+example
我想将分隔符从 + 更改为 - 以获得类似的内容
www.example.com/this-is-my-example
我知道另一个线程: 如何改变Zend Url的分隔符?正如记录的一种方法,我尝试过但没有成功。
关于如何做到这一点的详尽解释将不胜感激。
编辑2:如果有人感兴趣的话,我知道问题出在哪里,它来自于 url 的组装方式,它使用 urlencode 来转换所有非字母数字字符,期望 - 和 _ 以及空格为 +,除了替换之外没有办法覆盖它角色手动创建 url(如 Maxime 建议)或创建自定义 url 函数来替换字符(如 aporat 建议)...
谢谢!
解决方案
如果你真的想这样做,你可以延长库存 Zend_View_Helper_Url
查看助手并将您的 url 逻辑添加到您的视图助手中。
<?php
namespace Application\View\Helper;
class MyUrl extends \Zend_View_Helper_Url
{
/**
* Generates an url given the name of a route.
*
* @access public
*
* @param array $urlOptions Options passed to the assemble method of the Route object.
* @param mixed $name The name of a Route to use. If null it will use the current Route
* @param bool $reset Whether or not to reset the route defaults with those provided
* @return string Url for the link href attribute.
*/
public function myUrl(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
{
return str_replace('+', '-', parent::url($urlOptions, $name, $reset, $encode));
}
}
然后加载新的视图助手就可以了:
$helper = new \Application\View\Helper\MyUrl;
$this->view->registerHelper($helper, 'myUrl');
其他提示
不幸的是,在调用之前您无法设置任何内容 url(...)
功能来实现你想做的事情。原因是在组装URL时,它使用了php urlencode(...)
功能。
也就是说,您仍然有很多选择:
1)你根本不使用 url(...)
函数并手动创建 URL。(最佳选择)
2)你创建一个新的助手,其行为类似于 url(...)
但要对函数添加额外的更改以实现您想要执行的操作。
3) 获取 url(...) 函数的输出并执行 str_replace
改变 +
和 -
. 。(我不推荐这个选项)
就我个人而言,我手动创建所有 URL 以避免此类问题。
不隶属于 StackOverflow