Search code examples
phpcakephpmodels

CakePHP 3.X Models Usage


So, I am a pretty new PHP developer and have little idea how to use Models in CakePHP. I come from a strong Android and java background so i am very familiar with the MVC framework but after searching and digging through other people's php, i find that the usage of the model varies a lot. I want to get a solid answer.

Would i use the models in CakePhp the same as i would a class in java (create instances) and also as a connection to a database? Or would i separate models from "java classes" and have different uses for both.

Thanks in advance.


Solution

  • Model is a layer

    Model doesn't refer to a single type of class, it's a pretty high level term an describes the layer in MVC that should implement all your data processing / fetching. Depending on the framework each of it has it's own structure and kind of model layer, they all differ more or less.

    Basically this can be simplified by "Fat models skinny controllers". Your controller should handle the request and pass required info to the model layer and get the data back it needs to display or do something else with it.

    In CakePHP

    Would i use the models in CakePhp the same as i would a class in java (create instances) and also as a connection to a database? Or would i separate models from "java classes" and have different uses for both.

    I really recommend you to do the basic tutorial and read through the ORM section of the book.

    You can put whatever you want in the model layer. For example I have classes that just return some data and others that contain static data for navigation items for example. But lets stick to table objects for now. In cake a table object contains a reference to a connection object that contains the actual connection. Explaining this here doesn't make any sense, read the ORM section. :)

    I have no idea what exactly you want to do so I can't give you any more detailed advice on what you can or should do.