• [Yii Framework] How to build a friendly url in Yii


    Here i will take stay.com for example, because this website i think is a very beatiful and flexiable website.

    For example, under her home page, the urls of the citys are as: http://www.stay.com/london, that is to say, there is not controller name before the city's name, i use Yii blog to test how to do it.

    1. Set the urlManager of main.php
    protected/config/main.php

    代码
    'urlManager'=>array(
    'class'=>'CUrlManager',
    'urlFormat'=>'path',
    //'urlSuffix'=>'.html',//Please note that, this value can NOT be used, i will descript the reason below.
    'showScriptName'=>false,
    'caseSensitive'=>false,//it makes route case-insensitive.
    'rules'=>array(
    'posts/<tag:.*?>'=>'post/index',
    '<controller:\w+>'=>'<controller>',
    '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
    '<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>',
    '/'=>'post',
    '<titile:.*?>'=>'post/view',
    )
    ,
    )
    ,

    You have to be aware these:
    A. the value '<titile:.*?>'=>'post/view' has to be the last one, other wise, it will change other url request!

    B. Without '/'=>'post', it will cause "The requested page does not exist.", at the same time, this value has to been locate in the current place.

    C. About '<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>', in fact that, I haven't try to find whether or not there is <module:\+>, :P but after adding, the module can run without error (for example, the image of captcha can display or not in a module.)

    2. In the PostController a glocal controller
    protected/controllers/PostController.php

    代码
    <?php
    class PostController extends CController
    {
    public function actionView()
    {
    //That is why we can NOT set the 'urlSuffix'=>'.html' above in the route
    $arrUrl = explode('/', Yii::app()->request->url);
    $title = urldecode($arrUrl[count($arrUrl)-1]);

    //As you can know, the code below will make slow to every request.
    $criteria = new CDbCriteria;
    $criteria->condition = "title = '".$title."'";
    $criteria->limit = 1;
    $model = Post::model()->find($criteria);
    $this->render("view", array("model"=>$model));
    }
    }

    3. Modify the posts model
    protected/models/Post.php,find this function: getUrl(), change it to:

    public function getUrl()
    {
    return Yii::app()->createUrl($this->title);
    }
    Then in any view file, you can call this method via $model->getUrl() to create the current model link.

    Have fun with Yii! :)

  • 相关阅读:
    Tomcat架构解析(五)-----Tomcat的类加载机制
    session与cookie
    freemarker常用标签解释遍历
    freemarker常用标签解释三
    freemarker常用标签解释二
    freemarker常用标签解释
    禁止浏览器自动填充
    使用cookie实现自动登录
    长连接和短连接
    filter防止xxs攻击
  • 原文地址:https://www.cnblogs.com/davidhhuan/p/1863775.html
Copyright © 2020-2023  润新知