FuelPHP 路由

fuelphp 路由

 

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

 

配置

路由配置文件位于 fuel/app/config/routes.php。默认的 routes.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 作为默认值。我们将在 request 和 response 章节中学习 request 类。

 

结果

 

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'))), 
);

下一节:fuelphp 请求和响应

fuelphp 教程

相关文章