控制器
新建控制器
在tp/application/index/controller下新建User.php
<?php
namespace app\index\controller;
class User
{
public function index()
{
return "user:index";
}
public function read()
{
return"wo shi fei wu";
}
}
访问:http://tp.com/index.php/index/user/index
注意
- 文件名首字母大写,文件名采用驼峰命名
- 控制器名字必须跟文件名对应
- 命名空间必须和文件名对应
- 如果控制名字采用驼峰命名比如UserInfo访问时对应为user_info
加载页面
1.系统view类
<?php
namespace app\index\controller;
class User
{
public function read()
{
$view=new \think\View();
return $view->fetch();
}
}
2.系统controller类
<?php
namespace app\index\controller;
use think\Controller;
class User extends Controller
{
public function read()
{
return $this->fetch();
}
}
3.系统方法
<?php
namespace app\index\controller;
class User
{
public function read()
{
return view();
}
}
数据返回
- 在应用配置文件中可以设置数据返回格式
初始化
-
调用其他方法时初始化方法先被调用,必须继承系统控制器才能用
<?php namespace app\index\controller; use think\Controller; class User extends Controller { //该方法会现先被调用 public function _initialize() { echo "init"; } public function read() { return $this->fetch(); } }
-
作用
可以用来提取控制器下公共代码
可以用于后台权限把控
前置方法
-
需要继承控制器
<?php namespace app\index\controller; use think\Controller; class User extends Controller { //在方法调用前先调用这两个方法 protected $beforeActionList=[ 'read','one', ]; public function index() { return "user-index"; } public function one() { echo "one"; } public function read() { echo "read"; } }
页面跳转
- 基于系统类,必须继承系统控制器
- 所在路径 tp/thinkphp/library/traits/controller/jump.php
跳转方式
<?php
namespace app\index\controller;
use think\Controller;
class login extends Controller
{
public function index()
{
return view();
}
public function check()
{
$username=$_POST['username'];
$password=$_POST['password'];
if(($username==='Tim')&&($password==='123456'))
{
//成功跳转
$this->success('successfully!!',url('index/index'));
}
else{
//失败跳转
$this->error('error!!');
}
}
}
修改跳转页面
修改模板页面
1.找到配置文件application/config
dispatch_success_tmpl和dispatch_error_tmpl
2.找到thinkphp/tpl/dispatch_jump.tpl
3.跳转方法给模板页面的数据
- code:返回状态码 成功1 失败0
- msg: 返回提示信息
- wait:等待时间
- URL:到达的页面,默认返回上一个页面
- data:用户返回的数据
4.修改模板页面thinkphp/tpl/dispatch_jump.tpl
自定义页面
可以在tp/thinkphp/tpl下自定义目录xxx.tpl
然后修改 配置文件
application/config中的
dispatch_success_tmpl和dispatch_error_tmpl参数,把dispatch_jump.tpl替换成xxx.tpl
注意要用tpl后缀
重定向
作用
重定向就是通过各种方法将各种网络请求重新定个方向跳转到其他位置
<?php
namespace app\index\controller;
use think\Controller;
class User extends Controller
{
public function red()
{
//调用red方法会调用index下的type方法,带上参数id 和name
$this->redirect('index/type',['id'=>100,'name'=>'111']);
}
}
空操作
<?php
namespace app\index\controller;
use think\Controller;
class User extends Controller
{
//乱输入方法默认返回首页
public function _empty()
{
$this->redirect('index/index');
}
}
空控制器
在controller目录下新建Error.php
//在空控制器下定义空操作就可以避免乱输控制器和方法
<?php
namespace app\index\controller;
use think\Controller;
class Error extends Controller
{
public function index()
{
$this->redirect('index/index');
}
//乱输入方法默认返回首页
public function _empty()
{
$this->redirect('index/index');
}
}
- 网站上线的时候每个控制器必须写一个空操作,前台后台都要写空控制器