在寫程序的時候很難避免重復執行相同或相似的代碼,用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多次重復的代碼的簡化方法