Phalcon7 路由的使用

2018-10-21 07:15 更新

Router 组件允许定义用户请求对应到哪个控制器或 Action。Router 解析 URI 以确定这些信息。路由器有两种模式:MVC模式和匹配模式(match-only)。第一种模式是使用MVC应用程序的理想选择。

定义路由

Phalcon\Mvc\Router 提供了一套先进的路由功能。在MVC模式中,你可以自定义路由规则,对应到你需要的 controllers/actions 上。路由的定义如下:

<?php

use Phalcon\Mvc\Router;

// Create the router
$router = new Router();

// Define a route
$router->add(
    "/admin/users/my-profile",
    array(
        "controller" => "users",
        "action"     => "profile"
    )
);

// Another route
$router->add(
    "/admin/users/change-password",
    array(
        "controller" => "users",
        "action"     => "changePassword"
    )
);

$router->handle();

add() 方法接受一个匹配模式作为第一个参数,一组可选的路径作为第二个参数。如上,如果URI就是/admin/users/my-profile的话, 那么 “users” 控制的 “profile” 方法将被调用。当然路由器并不马上就调用这个方法,它只是收集这些信息并且通知相应的组件( 比如 Phalcon\Mvc\Dispatcher )应该调用这个控制器的这个动作。

一个应用程序可以由很多路径,一个一个定义是一个非常笨重的工作。这种情况下我们可以创建一个更加灵活的路由:

<?php

use Phalcon\Mvc\Router;

// Create the router
$router = new Router();

// Define a route
$router->add(
    "/admin/:controller/a/:action/:params",
    array(
        "controller" => 1,
        "action"     => 2,
        "params"     => 3
    )
);

在上面的例子中我们通过使用通配符定义了一个可以匹配多个URI的路由,比如,访问这个URL(/admin/users/a/delete/dave/301),那么:

Controllerusers
Actiondelete
Parameterdave
Parameter301

默认占位符对应正则表达式

PlaceholderRegular ExpressionUsage
/:module/([\\w0-9\\_\\-]+) | Matches a valid module name with alpha-numeric characters only
/:controller/([\\w0-9\\_\\-]+) | Matches a valid controller name with alpha-numeric characters only
/:action/([\\w0-9\\_\\-]+) | Matches a valid action name with alpha-numeric characters only
/:params(/.*)*Matches a list of optional words separated by slashes. Only use this placeholder at the end of a route
/:namespace/([\\w0-9\\_\\-]+) | Matches a single level namespace name
/:int/([0-9]+)Matches an integer parameter

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号