一、控制器的定义
ThinkPHP框架的控制器定义在application文件夹下的子目录中。例如:
在application文件夹下创建index模块,在index文件夹下创建controller文件夹存放index模块下的控制器文件。
//application/index/controller/Index.php
<?php
namespace app\index\controller;//定义命名空间
use think\Controller;//引入控制器类
class Index extends Controller{
public function index(){
return "Hello World";
}
}
二、路由和控制器
路由和控制器是通过定义路由规则来建立联系的。
Route::get("/index", "index/Index/index");
三、参数和控制器
对于在路由中传入的参数,将以路由定义的参数顺序进行传入处理函数
例:
//route.php中定义的路由
Route::get("/index/:id/:name", "index/Index/index");
//application/index/controller/Index.php定义的控制器
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller{
public function index($id, $name){
return $id . $name;
}
}
四、依赖注入和控制器
对于在函数中需要注入的类,应先于路由参数进行定义。
例:
//route.php中定义的路由
Route::get("/index/:id/:name", "index/Index/index");
//application/index/controller/Index.php定义的控制器
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;//依赖注入
class Index extends Controller{
public function index(Request $request, $id, $name){
return $id . $name;
}
}