Thinkphp5学习009-项目案例-学生列表-控制器中的代码
在这个学生管理系统中,除了登录页面不需要判断是否已经登录外,其他所有页面都要首先判断是否已经正常登录,否则不允许操作数据
所以,我们在构造方法中,使用了会话管理:Session::has() 来判断 "admin" 的存在性。如果不存在“admin",说明还未正常登录,强制跳转到登录页面
所以我们要写一个控制器来先检测是否登陆。
在application新建common\controller中写一个控制器AdminBase.php控制器类的代码如下
<?php
namespace app\common\controller;
use think\Controller;
use think\Request;
use think\Session;
class AdminBase extends Controller
{
function __construct(Request $request = null)
{
parent::__construct($request);
if(!Session::has('admin')){
$this->error('请先登录,然后操作','index/index/index');
}
}
}
最终AdminBase控制器,还是继承了Controller
根据继承的传递性,Student控制器最终也继承了Controller
php在继承父类时,构造方法的使用非常特殊,子类如果有了自己的构造方法,就不会执行父类的构造方法,但是,在tp5系统中,必须执行Controller中的构造方法,所以我们就必须执行:
parent::__construct($request);
显示的执行父类的构造方法
二. 学生列表-控制器中的代码Student.php
Student类要继承AdminBase类,
所以要use app\common\controller\AdminBase;
在Student类的all()方法中,我们使用
$data = Db::name('student')->select();
对数据表student进行查询,返回所有记录。
再向模板文件student.html传递一个变量student,变量中的值是$data
<?php
namespace app\index\controller;
use app\common\controller\AdminBase;
use think\Db;
use think\exception\PDOException;
/**
* 学生控制器
* 主要实现学生的添加、修改、删除、显示
*/
class Student extends AdminBase
{
//显示所有学生列表
public function all()
{
//select方法,返回二维数组
$data = Db::name('student')->select();
$this->assign('student', $data);
return $this->fetch();
}
}
三.整体效果如下:
===今天的学习到此===