ThinkPHP控制器的使用:
一、控制器如何加载页面
1、系统View类
$view=new \think\View;
return $view->fetch();
use think\View;
$view=new View();
return $view->fetch();
2、系统Controller类
a、需要继承系统控制器类
use think\Controller;
// 声明控制器
class User extends Controller
b、直接使用系统控制器类的方法
return $this->fetch();
3、系统函数
return view();
二、数据输出
1、在应用配置文件中可以设置数据返回格式
'default_return_type' => 'json', #默认是html
2、ajax请求的时候如何返回数据
'default_ajax_return' => 'json',
三、控制器的初始化
1、控制器初始化方法必须继承系统控制器
// 控制器的初始化方法
public function _initialize(){
echo "我是初始化方法";
}
2、只要调用控制器下的任意方法,都会先找初始化方法
3、控制器初始化方法的使用
a、可以用来提取控制器下公共的代码
b、后台权限把控
四、前置操作
1、前置方法 把一些公共的设置提取成方法进行调用
2、前置方法必须结合系统控制器
3、核心设置
// 前置方法属性
protected $beforeActionList=[
'one',
// 不想让谁使用前置方法two
'two'=>['except'=>"index"],
// 仅仅可以让谁使用前置方法three
'three'=>['only'=>'index'],
];
五、页面跳转
1、页面跳转基于系统控制器类,所以控制器必须继承系统控制器
2、方法所在路径
C:\wamp64\www\tp5\thinkphp\library\traits\controlle\Jump.php
3、跳转方式
a、成功跳转
// $this->success(提示信息,跳转地址,用户自定义数据,跳转跳转,header信息);
// 跳转地址未设置时 默认返回上一个页面
$this->success('跳转成功',url('index/index'));
b、失败跳转
$this->error('登录失败');
4、跳转方法给模板页面的数据
a、$code 返回的状态码 成功 1 失败 0
b、$msg 页面的提示信息
c、$wait 等待时间
d、$url 制定跳转页面 默认返回上一个页面
e、$data 用户返回的数据
5、相关配置文件
// 默认跳转页面对应的模板文件
'dispatch_success_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
'dispatch_error_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
6、修改成功和失败的模板页面
a、修改默认文件
01)、默认文件位置
C:\wamp64\www\tp5\thinkphp\tpl\dispatch_jump.php
02)、根据原有代码进行修改
在成功失败模板页面进行修改
b、用户自定义页面跳转模板
01)、修改配置文件
'dispatch_success_tmpl' => THINK_PATH . 'tpl' . DS . 'success.tpl',
'dispatch_error_tmpl' => THINK_PATH . 'tpl' . DS . 'error.tpl',
02)、在系统模板目录下 (C:\AppServ\www\tp5\thinkphp\tpl) 新建 success.php 和error.php
03)、自定义书写跳转页面
六、重定向
1、作用:
重定向(Redirect)就是通过各种方法将各种网络请求重新定个方向转到其它位置
2、使用:
redirect('跳转地址','其他参数',code,'隐士参数');
$this->redirect('index/index',['id'=>100,'name'=>'abc'])
七、空控制器和空操作
1、空操作# 主要解决一些用户恶意的地址栏输入,报错影响交互
public function _empty(){
$this->redirect('index/index');
}
2、空控制器
// 声明命名空间
namespace app\index\controller;
use think\Controller;
// 声明控制器
class Error extends Controller{
// index
public function index(){
$this->redirect('index/index');
}
// 空操作
public function _empty(){
$this->redirect('index/index');
}
}
3、注意:
a、网站上线的时候每一个控制器都必须添加空操作
b、不论前台后台都需要写一个空控制器
八、资源控制器
1、使用命令行创建控制器
php think make:controller app\index\controller\Goods
2、资源控制器一般配合资源路由使用