在写程序的时候很难避免重复执行相同或相似的代码,用thinkphp同样会有重复代码,对于这些多次重复使用的程序,thinkphp有内置的办法,也有我们手动创建的方法来精简。
1、利用类继承
父类:EmptyController.class.php
namespace Home\Controller;
use Think\Controller;
class EmptyController extends Controller {
public $var;
public function __construct(){
parent::__construct();
$this->var='';//这里可以定义全局变量 在子类中直接调用$this->var;
$this->assign($data,'xxx');//这里是公共输出变量,在所有前端页面中都可以直接访问{$data}
}
public function code() {
//这里是重复要执行的内容
}
}
子类:IndexController.class.php,直接集成EmptyController.class.php,即可直接调用父类中定义和分配的变量,及相关方法;
namespace Home\Controller;
class IndexController extends EmptyController {
public function index(){
echo $this->var;//直接调用父类定义的变量
//$this->code();//父类的方法,这个前后台都可调用
//前端可以直接访问{:U('Index/code')},虽然本类没有定义,但父类定义了。当然,本类中可以重定义
}
}
2、利用_initialize(),该类中所有方法执行之前都要先执行这里的内容
protected function _initialize(){
$Login=cookie('userid');
if(!$Login){
$this->redirect('Basic/login');
}
if(!cookie('s')){
Alt('您需要先完善主体信息!',U('Basic/about'));
}
}
3、利用函数
function fun(){
//这里是内容
}
public function index(){
fun();
}
4、利用方法
public function parkShow($id){
$d=$this->cont('Park',$id);
$this->assign($arr)->display();
}
private function cont($table,$id){
$id=str_ireplace('t-','',$id);
$d=M($table)->find($id);
if(!$d){
Alt('错误!您查阅的页面不存在');
}
calcX($table,$id,1);//表名,id,view+1
$d['editor']=true;
$d['pinglun']=M('Comment')->where('s=1 and `table`="'.$table.'" and toid='.$id)->order('id desc')->select();
if(cookie('name') && cookie('userid')){
$d['rep']=M('Comment')->field('id,cont')->where('`table`="'.$table.'" and toid='.$id.' and uid='.cookie('userid'))->find();
}
return $d;
}
利用类、函数解决thinkphp多次重复的代码的简化方法大致就有上面这样四种,只是有的时候可能需要变通一下,比如代码4,如果在parkShow()中先生成了$d,那么就需要合并才可以达到想要的效果。
public function parkShow($id){
$d=M('xx')->find($id);
$d=array_merge($d,$this->cont('xx',$id));
$this->assign($arr)->display();
}
© 致远 2020-11-29,原创内容,转载请注明出错:利用类、函数解决thinkphp多次重复的代码的简化方法