Yii开发jedis!
我正在研究一些旧的Yii项目,必须向他们添加一些功能.Yii是非常合乎逻辑的框架,但它有一些我无法理解的东西.也许我还没理解Yii-way.所以我将逐步描述我的问题.对于不耐烦的人 - 最后简要提问.
简介:我想在我的项目中添加人类可读的URL.现在网址如下:www.site.com/article/359
我希望它们看起来像这样:www.site.com/article/how-to-make-pretty-urls
非常重要:旧文章必须在旧版本上可用格式化URL和新的 - 关于新URL.
第1步:首先,我在config/main.php中更新了重写规则:
'<controller:\w+>/<id:\S+>' => '<controller>/view',
Run Code Online (Sandbox Code Playgroud)
我在文章表中添加了新的texturl列.因此,我们将在这里存储人类可读的新文章的部分内容.然后我用texturl更新了一篇文章进行测试.
第2步:在应用显示文章的actionView的ArticleController所以我加入那里preproccessing ID参数验证码
if (is_numeric($id)) {
// User try to get /article/359
$model = $this->loadModel($id); // Article::model()->findByPk($id);
if ($model->text_url !== null) {
// If article with ID=359 have text url -> redirect to /article/text-url
$this->redirect(array('view', 'id' => $model->text_url), true, 301);
}
} else {
// User try to get /article/text-url
$model = Article::model()->findByAttributes(array('text_url' => $id));
$id = ($model !== null) ? $model->id : null ;
}
Run Code Online (Sandbox Code Playgroud)
然后开始遗留代码:
$model = $this->loadModel($id); // Load article by numeric ID
// etc
Run Code Online (Sandbox Code Playgroud)
它的工作原理完美!但...
第3步:但我们有许多ID参数的动作!我们要做什么?使用该代码更新所有操作?我认为这很难看.我找到了CController :: beforeAction方法.看起来不错!所以我声明beforeAction并在那里放置ID preproccess:
protected function beforeAction($action) {
$actionToRun = $action->getId();
$id = Yii::app()->getRequest()->getQuery('id');
if (is_numeric($id)) {
$model = $this->loadModel($id);
if ($model->text_url !== null) {
$this->redirect(array('view', 'id' => $model->text_url), true, 301);
}
} else {
$model = Article::model()->findByAttributes(array('text_url' => $id));
$id = ($model !== null) ? $model->id : null ;
}
return parent::beforeAction($action->runWithParams(array('id' => $id)));
}
Run Code Online (Sandbox Code Playgroud)
是的,它适用于两种URL格式,但它执行actionView TWICE并显示两次页面!我该怎么办?我完全糊涂了.我有没有选择正确的方法来解决我的问题?
简而言之:我可以在执行任何操作之前执行ID(GET参数),然后使用仅修改的ID参数运行请求的操作(一次!)?
Vib*_*haJ 13
最后一行应该是:
return parent::beforeAction($action);
Run Code Online (Sandbox Code Playgroud)
还问你我没有得到你的步骤:3.
正如你所说,你有很多控制器,你不需要在每个文件中编写代码,所以你使用的是beforeAction:但你只有text_url与所有控制器的文章相关?
$model = Article::model()->findByAttributes(array('text_url' => $id));
Run Code Online (Sandbox Code Playgroud)
=====更新回答======
我已更改此功能,请立即查看.
如果$ id不是nummeric,那么我们将使用model找到它的id并设置$ _GET ['id'],因此在进一步的控制器中它将使用该numberic id.
protected function beforeAction($action) {
$id = Yii::app()->getRequest()->getQuery('id');
if(!is_numeric($id)) // $id = how-to-make-pretty-urls
{
$model = Article::model()->findByAttributes(array('text_url' => $id));
$_GET['id'] = $model->id ;
}
return parent::beforeAction($action);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13486 次 |
| 最近记录: |