企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
```php <?php /** * 一个控制器代码示例 */ namespace app\index\controller; use think\Controller; // 继承了think\Controller类之后,可以直接使用think\View及think\Request类的方法 class Index extends Controller { // 定义某个方法为其他方法的前置操作 protected $beforeActionList = [ 'first', // 不写默认为所有方法的前置操作,first方法在所有方法之前执行 'second' => ['except'=>'hello'], // second为除了hello之外其他方法的前置操作 'three' => ['only'=>'hello,data'], // three仅为hello和data方法的前置操作 ]; // 构造方法 public function _initialize() { echo 'init<br/>'; } // 首页 public function index() { // 获取包含域名的完整URL地址渲染到视图(下面两步可以用view助手函数替代) $this->assign('domain',$this->request->url(true)); return $this->fetch('index'); } /************************************ * 跳转与重定向(默认等待3秒跳转,可以设置) * ********************************/ // 默认跳转页面模板都为:THINK_PATH . 'tpl/dispatch_jump.tpl' // success与error模板更改方法,在配置文件中: //默认错误跳转对应的模板文件 'dispatch_error_tmpl' => APP_PATH . 'tpl/dispatch_jump.tpl', //默认成功跳转对应的模板文件 'dispatch_success_tmpl' => APP_PATH . 'tpl/dispatch_jump.tpl', // 也可以直接使用项目中的模板文件 //默认错误跳转对应的模板文件 'dispatch_error_tmpl' => 'public/error', //默认成功跳转对应的模板文件 'dispatch_success_tmpl' => 'public/success', // 更加详细的用法,比如向跳转模板中传一些参数,参考官方手册跳转与重定向一章 public function add() { if($result){ //设置成功后跳转页面的地址,默认的返回页面是$_SERVER['HTTP_REFERER'] $this->success('新增成功', 'User/list'); } else { //错误页面的默认跳转页面是返回前一页,通常不需要设置 $this->error('新增失败'); } // 重定向相关用法 //重定向到News模块的Category操作 $this->redirect('News/category', ['cate_id' => 2]); //重定向到指定的URL地址 并且使用302 $this->redirect('http://thinkphp.cn/blog/2',302); // 在重定向的时候通过session闪存数据传值 $this->redirect('News/category', ['cate_id' => 2], 302, ['data' => 'hello']); // 使用redirect助手函数还可以实现更多的功能如: // 记住当前的url之后跳转 redirect('News/category')->remember(); // 跳转到上次记住的url redirect()->restore(); } /********************************** * 空操作(访问一个该控制器中不存在的操作方法时默认调用空操作) ************************************/ // http://serverName/index/city/beijing/,_empty方法的参数即为传入的操作名称 // V5.0.2+开始,空操作方法不需要任何参数,如果要获取当前的操作方法名,直接调用当前请求对象来获取,你也可以使用依赖注入 public function _empty($name) { //把所有城市的操作解析到city方法 return $this->showCity($name); } //注意 showCity方法 本身是 protected 方法 protected function showCity($name) { //和$name这个城市相关的处理 return '当前城市' . $name; } } ```