这是蛋糕PHP 1.3
我在appcontroller中有一个名为setLog()的方法。我正在尝试将此方法作为所有控制器的通用方法。但是当在另一个控制器(委员会控制器)中调用它时,它会显示
调用未定义的方法CommitteesController :: setLog()
我需要知道如何正确调用此函数。
App::import('Controller', 'ActionLogs');
class AppController extends Controller {
public function setLog($action,$remark,$status){
$logs = new ActionLogsController;
$logs->constructClasses();
$data = ['action'=>$action,'user'=>$this->Auth->user('id'),'remark'=>$remark,'status'=>$status];
$logs->add($data);
}
}
function add() {
if (!empty($this->data)) {
$this->Committee->create();
if ($this->Committee->save($this->data)) {
//create a log for success
$this->setLog('add new committee',json_encode($this->data),1);
$this->Session->setFlash(__('The committee has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The committee could not be saved. Please, try again.', true));
//create a log for failed
$this->setLog('add new committee',json_encode($this->data),0);
}
}
$committeeTypes = $this->Committee->CommitteeType->find('list');
$cond = array('group_id' => 2,'is_active' => '1');
$cond2 = array('group_id' => 4,'is_active' => '1');
$secretaryUserids = $this->Committee->SecretaryUserid->find('list', array('conditions' => $cond));
$assistantSecretaryUserids = $this->Committee->AssistantSecretaryUserid->find('list', array('conditions' => $cond2));
$this->set(compact('committeeTypes', 'secretaryUserids', 'assistantSecretaryUserids'));
}
答案 0 :(得分:0)
您可以选择以下两项之一:
继承性:创建一个BaseController,您可以在其中放置控制器共享的所有方法:
class BaseController extends Controller
{
public function setLog()
{
// Code here
}
}
class YourController extends BaseController
{
public function yourControllerFunction()
{
$this->setLog();
}
}
setLog()
必须是公共的或受保护的,而不是私有的,否则它只能在BaseController内部工作。
您的AppController
可能就是我在上面所说的BaseController
,所以您要做的就是简单地
class YourController extends AppController
,您将可以使用setLog()
函数。
共享功能的另一种方法是使用特征:
trait LoggerTrait
{
public function setLog()
{
// Code here
}
}
class YourController extends Controller
{
use LoggerTrait;
public function yourControllerFunction()
{
$this->setLog();
}
}