Where to set the controller's parent class in CakePHP?

I have two controllers that share most of their code (but should nevertheless be different controllers). The obvious solution (at least for me) is to create a class and create two controllers on it. The thing is ... where can I say this? Now I have this in app_controller.php, but it's kind of messy.

+4
source share
2 answers

In the cake, components are used to store logic that can be used by several controllers. The directory is / app / controller / components. For example, if you have some kind of general utility logic, you will have a UtilComponent object 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 add:

 var $components = array('Util'); 

Then you call methods like:

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

Additional Information:

Documentation

+9
source

Btw, if the reason that "they must be separate controllers" is the required URLs. Remember that you can use routing:

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

Source: https://habr.com/ru/post/1277175/


All Articles