paradoja
paradoja

Reputation: 3090

Where to put controller parent class in CakePHP?

I have two controllers which share most of their code (but must be, nonetheless, different controllers). The obvious solution (to me, at least) is to create a class, and make the two controllers inherit from it. The thing is... where to put it? Now I have it in app_controller.php, but it's kind of messy there.

Upvotes: 4

Views: 1057

Answers (2)

Alexander Morland
Alexander Morland

Reputation: 6434

Btw, if the reason for "they must be seperate controllers" is the URLs you require. Remember you can use routing:

Router::connect('/posts', array('controller' => 'posts', 'action' => 'index'));
Router::connect('/comments', array('controller' => 'posts', 'action' => 'list_comments'));

Upvotes: 4

tyshock
tyshock

Reputation: 1311

In cake, components are used to store logic that can be used by multiple controllers. The directory is /app/controllers/components. For instance, if you had some sharable utility logic, you would have an object called UtilComponent and a file in /app/controlers/components called UtilComponent.php.

<?php
class UtilComponent extends Object {
    function yourMethod($param) {
        // logic here.......

        return $param;
    }
}
?>

Then, in your controller classes, you would add:

var $components = array('Util');

Then you call the methods like:

$this->Util->yourMethod($yourparam);

More Info:

Documentation

Upvotes: 9

Related Questions