how to create multiple models against multiple function in single controller in CakePHP

333 Views Asked by At

i think, In "CakePHP" one model is against each controller but i have multiple functions in single controller and each function represent different page and database table. i.e

public function manage_categories(){}
public function manage_sub_categories(){}

above 2 functions are in Admin Controller but now the issue is how to create model against each function to represent database. each function has unique attributes in database. One thing more either model name should be same to controller name "admin" or this name will be same as functions name. while in normal circumstances model name is same to controller name.

"Users" model name is used against "UsersController" kindly guide me ti resolve above said issue. i tried enough to solve it bot couldn't. Thanks in advance.

1

There are 1 best solutions below

2
On BEST ANSWER

If you have two database tables it would be logical and best practice in terms of SoC to have two controllers instead of throwing a lot different things that don't belong into the same domain into a single controller.

Sometimes when you just want to use a part of data from an associated model you can access it through the associations:

$this->Model->SubModel->foo();

Also you say you have an admin controller which is a working but not very good approach. Instead CakePHP features prefix routing. So an action accessed like /admin/categories/some_action will route to the CategoriesController some_action() action.

"Users" model name is used against "UsersController"

Is wrong, by convention models should be named singular, not plural. Your UsersController won't find an Users model because it's looking for an User model.

And stay away from Model::query(), use the ORM instead as much as you can.

public function manage_categories(){}
public function manage_sub_categories(){}

Should become:

class CategoriesController extends AppController {
    public function admin_index() { /*...*/ }
}
class SubCategoriesController extends AppController {
    public function admin_index() { /*...*/ }
}

But assuming that sub-categories belong to a category which is the same table I don't see a need for a second model or second controller at all.