Site icon 时鹏亮的Blog

零基础学Phalcon 9 router 组件

请知悉:本文最近一次更新为 7年 前,文中内容可能已经过时。

本节对应书里的The router component。
原文翻译整理如下:

router(路由)组件帮助我们将友好的URL映射到我们的控制器和操作。
默认情况下,如果在Web服务器中启用了重写模块(rewrite),拟将能够访问名为Post的控制器并读取操作,如网址所示:http://www.learning-phalcon.localhost/post/read。 我们的代码看起来像这样:

<?php
class PostController extends PhalconMvcController
{
public function readAction()
{
// get the post
}
}

然而,有时如果你需要将网址翻译成多种语言,或者你需要以不同的方式在代码中定义网址,上述代码就不再适用了。 以下是对此需求,router(路由)组件的使用示例:

<?php
$router = new PhalconMvcRouter();
// Clear the default routes
$router->clear();
$st_categories = array(
'entertainment',
'travel',
'video'
);
$s_categories = implode('|', $st_categories);
$router->add('#^/('.$s_categories.')[/]{0,1}$#', array(
'module' => 'frontend',
'controller' => 'post',
'action' => 'findByCategorySlug',
'slug' => 0
));

在前面的示例中,我们将所有类别映射到controller(控制器) post,请求的操作(动作)映射给action findByCategorySlug。 路由组件允许我们为我们的URL使用正则表达式。通过使用preg_match函数匹配,以如下代码实现:

$url = 'http://www.learning-phalcon.localhost/video';
preg_match('#^/(entertainment|travel|video)[/]{0,1}$#', $url);

通过访问http://www.learning-phalcon.localhost/video,请求将被转发到controller(控制器)post的findByCategorySlug操作上:

<?php
class PostController extends PhalconMvcController
{
public function findByCategorySlug()
{
$slug = $this->dispatcher->getParam('slug', array('string', 'striptags'), null);
// We access our model (entity) to get all the posts from this category
$posts = Posts::findByCategorySlug($slug);
if ($posts->count() > 0) {
$this->view->setVar('posts', $posts);
} else {
throw new Exception('There are no posts', 404);
}
}
}

getParam()方法有三个参数。 第一个参数是我们要搜索的名称,第二个参数是个过滤匹配用的数组,第三个参数是默认值,以防所请求的名称不存在或未设置的情况出现。

我们将在下一章讨论models(模型)。 这只是个如何使用路由的简单例子。

路由还支持请求方法的预检查。 你可以用来检查请求方法是POST,DELETE,PUT还是GET,代码如下:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'post') {
// process the information
}

虽然这是完全正确的,但代码并不友好。 Phalcon的路由有这种能力:你可以添加你期望的正确类型的请求,而不需要在代码中检查:

<?php
// Add a get route for register method within the user controller
$router->addGet('register', 'User::register');
// Add a post route for create method, from the user controller
$router->addPost('create', 'User::create');

以上是路由的基本用法。想了解更多关于该组件的信息,请阅读官方最新文档(http://docs.phalconphp.com/en/latest/reference/routing.html)。


如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《零基础学Phalcon 9 router 组件》相关的博文:

Exit mobile version