Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: AppController to access model of derivated Controller

Tags:

dry

cakephp

I want to implement shared "add" actions in the AppController. For this, I need to access the appropriate model of the derivated controller.

How do I do this?

like image 871
blinry Avatar asked Jan 13 '10 07:01

blinry


People also ask

How can I get current controller name in CakePHP 3?

To get the current, controller: $this->params['controller']

What is beforeFilter in CakePHP?

beforeFilter() executes functions that you NEED to be executed before any other action. Controller::beforeFilter() This function is executed before every action in the controller. It's a handy place to check for an active session or inspect user permissions. http://api.cakephp.org/2.3/class-Controller.html#_ ...

What is controller in CakePHP?

Advertisements. The controller as the name indicates controls the application. It acts like a bridge between models and views. Controllers handle request data, makes sure that correct models are called and right response or view is rendered.

How can I redirect to another page in CakePHP?

You can use: $this->redirect(array("controller" => "myController", "action" => "myAction", "param1" => "val1", "param2" => "val2", $data_can_be_passed_here), $status, $exit); Hope it helps!


1 Answers

The primary model class of a controller is stored in $this->modelClass, so you could do something like this:

class AppController extends Controller {
    function _add($data) {
        $this->{$this->modelClass}->save($data);
    }
}

class PostController extends AppController {
    function someFunction() {
        $this->_add($data);  // saves to Post model
    }
}
like image 164
deceze Avatar answered Oct 19 '22 02:10

deceze