When using tp3.3 for project development, many times the codes for additions, deletions, modifications and checks are basically the same, especially the controller part. However, the same code in each controller needs to be written again.
Learned design Pattern, what kind of pattern can be used in this case to reduce the amount of code duplication. It is best to use design pattern
For example, create rbac system:
This is the basic code for my administrator controller's add, delete, modify and check. Except for the different model classes created by the constructor, the basic add, delete, modify and check structures are similar. How can I reduce duplicate code? I hope an expert can give me some advice. Thank you. .
protected $_model;
public function __construct(){
parent::__construct();
$this->_model=new MannagerModel();
}
/**
* 管理員添加
*/
public function addC(){
if(IS_POST){
$data=I('post.');
$res=$this->_model->Store($data);
$this->redirectUrl($res,'listC');
}
$this->display();
}
/**
* 管理員列表顯示
* @return [type] [description]
*/
public function listC(){
$data=$this->_model->lists();
$this->assign('lists',$data);
$this->display();
}
/**
* 管理員刪除
* @return [type] [description]
*/
public function delC(){
$id=intval(I('get.id'));
$res=$this->_model->del($id);
//跳轉(zhuǎn)判斷函數(shù)
$this->redirectUrl($res);
}
/**
* 管理員更新
* @return [type] [description]
*/
public function editC(){
$id=intval(I('get.id'));
//where的數(shù)組形式
$where['id']=$id;
// 顯示舊數(shù)據(jù)
$old=$this->_model->lists($where);
$this->assign('old',$old);
//存儲(chǔ)新的數(shù)據(jù)
if(IS_POST){
$data=I('post.');
$res=$this->_model->edit($id,$data);
$this->redirectUrl($res,'listC');
}
$this->display();
}
Let’s be object-oriented. For basic additions, deletions, modifications and queries, write a base class. For special ones, just inherit the base class and override it