FuelPHP教程

FuelPHP 路由

路由映射请求一个指向特定控制器方法的 URI。在本章中,我们将详细讨论 FuelPHP 中 路由的概念。

配置

路由配置文件位于 fuel/app/config/routes.php。默认的 routes.php 文件定义如下-
<?php 
   return array ( 
      '_root_'  => 'welcome/index',   // The default route 
      '_404_'   => 'welcome/404',     // The main 404 route 
      'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'), 
   );
这里, _root_ 是预定义的默认路由,当应用程序请求根路径时会匹配,/e.g. http://localhost:8080/_root_ 的值是控制器和匹配时要解决的动作。 welcome/index 解析为 Controller_Welcome 控制器和 action_index 动作方法。同样,我们有以下保留路由。
root-未指定 URI 时的默认路由。 403-HttpNoAccessExc 时抛出找到了。 404-找不到页面时返回。 500-当发现 HttpServerErrorException 时抛出。

简单路由

将路由与请求 URI 进行比较。如果找到匹配项,则将请求路由到 URI。简单路由描述如下,
return array ( 
   'about'  => 'site/about', 
   'login' => 'employee/login', 
);
这里, about 匹配 http://localhost:8080/about 并解析控制器、Controller_Site 和操作方法 action_about
login 匹配 http://localhost:8080/login 并解析控制器 Controller_Login 和操作方法 action_login

高级路由

您可以在路由中包含任何正则表达式。 Fuel 支持以下高级路由功能-
:any-这匹配 URI 中从该点开始的任何内容,不匹配"无" :everything-像:any,但也匹配"nothing" :segment-这仅匹配 URI 中的 1 个段,但该段可以是任何内容 :num-匹配任何数字 :alpha-匹配任何字母字符,包括 UTF-8 :alnum-匹配任何字母数字字符,包括 UTF-8
例如,以下路由匹配 URI http://localhost:8080/hello/FuelPHP 并解析控制器、 Controller_Welcome 和操作 action_hello
'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'),
Controller_Welcome中对应的action方法如下,
public function action_hello() { 
   $this->name = Request::active()->param('name', 'World'); 
   $message = "Hello, " . $this->name;  
   echo $message; 
}
这里,我们使用 Request 类从 URL 中获取 name 参数。如果未找到名称,则我们使用 World 作为默认值。我们将在 RequestResponse 章节中学习 Request 类。

结果

Controller Welcome

HTTP 方法操作

FuelPHP 支持路由以匹配 HTTP 方法前缀的操作。以下是基本语法。
class Controller_Employee extends Controller { 
   public function get_index() { 
      // called when the HTTP method is GET. 
   }  
   public function post_index(){ 
      // called when the HTTP method is POST. 
   } 
}
我们可以根据配置文件中的 HTTP 动词将您的 URL 路由到控制器和操作,如下所示。
return array ( 
   // Routes GET /employee to /employee/all and POST /employee to /employee/create 
   ‘employee’ => array(array('GET', new Route(‘employee/all')), array('POST', 
      new Route(‘employee/create'))), 
);
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4