如何在URL上添加尾部斜杠

时间:2011-09-16 19:06:45

标签: php zend-framework

我希望我网站上的所有网址都在网址上有一个斜杠。我为Zend中的URLHelper创建了一个简单的扩展。现在它将所有单词分隔符更改为连字符( - )。添加附加斜杠的功能会很棒。注释掉的行(黑客)没有用。斜线最终被url编码。

我知道这必须是一个简单的解决方法,就在我的面前,但它正在逃避我。 :\

    class Ace_Helpers_Url 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 url(array $urlOptions = array(), $name = null, $reset = false, $encode = false)
   {
      if (is_array($urlOptions)) {
         foreach ($urlOptions as $index => $option) {
            $urlOptions[$index] = trim(strtolower(str_replace(' ', '-', $option)));
            #$urlOptions[$index] .= '/'; #Add trailing slash for continuity
         }
      }
      $router = Zend_Controller_Front::getInstance()->getRouter();
      return $router->assemble($urlOptions, $name, $reset, $encode);
   }
}

2 个答案:

答案 0 :(得分:3)

手动追加并不是那么难:

<?php echo $this->url(array(
        'controller' => 'index'
    )).'/'; ?>

如果您想避免网址编码,请查看网址助手的第四个参数:encode。将其设置为false并且不会对输入进行url编码,因此您可以执行以下操作:

<?php echo $this->url(array(
        'alias' => 'blog/2011/09/example-blog-entry'
    ),'alias',true,false); ?>

答案 1 :(得分:1)

我的解决方案基于this discussion

<强>应用/视图/助手/ Url2.php

class Zend_View_Helper_Url2 extends Zend_View_Helper_Url
{
    /**
     * Keeps Url()'s original params and their default values, so we don't have to
     * learn yet another method.
     */
    public function url2(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
    {
        return parent::url($urlOptions, $name, $reset, $encode) . '/';
    }
}

在某些控件中

echo $this->view->url2(array('controller' => 'index'));

或某些观点

echo $this->url2(array('controller' => 'index'));