How to use one Model in two controller


#1

Dear Friends,

I am using CakePHP friendsofcake's crud, I have two controllers UserController.php in /Admin and VendorsController.php in /Vendors. but these Both Controllers should use single Model CustomersTable.php.

Please let me know how should I achieve this?


#2

Cake’s MVC setup exists for a reason. Each table has its own controller. Using relations, you can make sure they are linked to eachother and queries can look up related data.
All controllers should be in folder Controller. Otherwise, Cake will not work.
So you will need CustomerController as well. Note that another controller can still look up data directly in other tables, using

use Cake\ORM\TableRegistry;

and

$SomeTable = TableRegistry::get(‘SomeTable’);


#3

Use $this->loadModel(‘Some Table’) instead of TableRegistry. TableRegistry is an evil.


#4

Can you please elaborate on “TableRegistry is an evil”?


#5

TableRegistry is (was) just a static wrapper for TableLocator , that has been removed in 3.6.
https://book.cakephp.org/3.next/en/appendices/3-6-migration-guide.html

You should not use any of static calls you can find in cake’s code or book as at some point they will just vanish leaving you with code that needs to be refactored before you will be able to update framework to recent version.


#6

If you are using Crud, then set the $modelClass property in the controller.

e.g.

class VendorController extends AppController
{
    public $modelClass = 'Users';
}