Loading models -- A question on how to do it properly

Hello,
What is the difference if I load a model versus table registry in another controller? If I am loading 1 entity, why is one better than the other?

$this->loadModel('Articles');

vs Entity
$articles = TableRegistry::get(‘Articles’);

https://book.cakephp.org/3.0/en/controllers.html#loading-additional-models

$this->loadModel can use defined connector to load “tables” other then RDB
TableRegistry is a connector used to load RDB tables, and is used as default connector for $this->loadModel

In case of RDB tables there is no any big difference, but I would stick to this->loadModel if you want to avoid refactoring in the future.

2 Likes

So the Table registry is a strict implementation of loading an RDB table, and load model is more conventional api?

Yes, TableRegistry is just a factory designated to load/create RDB tables , loadModel comes from ModelAwareTrait wich uses such factories to load any model. I would use a trait’s loadModel() over static TableRegistry as it seams to be more correct way, and TableRegistry should not be even mentioned in a book since we have that trait.

https://api.cakephp.org/3.5/source-class-Cake.Datasource.ModelAwareTrait.html