[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! :)

posted @ 2010-10-28 18:01 DavidHHuan 阅读(...) 评论(...) 编辑 收藏