Reputation: 11
This is cake php 1.3
I have a method in appcontroller called setLog(). I'm trying to use this Method as common for all controllers. but when call this in another controller (Committee Controller ) it says
Call to undefined method CommitteesController::setLog()
I need to know how to call this function correctly.
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'));
}
Upvotes: 1
Views: 595
Reputation: 758
You can choose one of the following two:
Iheritance: Create a BaseController where you can put all the methods shared by the controlers:
class BaseController extends Controller
{
public function setLog()
{
// Code here
}
}
class YourController extends BaseController
{
public function yourControllerFunction()
{
$this->setLog();
}
}
setLog()
has to be public or protected, not private, or it would work only inside BaseController.
It may be that your AppController
is what I'm calling BaseController
above, so what you have to do is simply
class YourController extends AppController
and you'll be able to use the setLog()
function.
Another way of sharing functions is using Traits:
trait LoggerTrait
{
public function setLog()
{
// Code here
}
}
class YourController extends Controller
{
use LoggerTrait;
public function yourControllerFunction()
{
$this->setLog();
}
}
Upvotes: 1