Php – MVC, where do the classes go

model-view-controlleroopphp

My understanding of the MVC is as follows (incase it's horribly wrong, I am afterall new to it)

  1. Models are the things that interface with the database
  2. Views are the design/layout of the page
  3. Controllers are where everything starts and are essentially the page logic

I'm using CodeIgniter but I would hazard a guess it's not just limited to that or possibly even just to PHP frameworks.

Where do I put global classes?

I may have a model for Products and I then run a query that collects 20 products from the database. Do I now make 20 models or should I have a separate class for it, if the latter, where do I put this class (other controllers will need to use it too)

Best Solution

Model is the wrong word to use when discussing what to do with products: each product is a value object (VO) (or data transfer objet/DTO, whatever fits in your mouth better). Value objects generally have the same fields that a table contains. In your case ProductVO should have the fields that are in Products table.

Model is a Data Access Object (DAO) that has methods like

findByPk --> returns a single value object
findAll --> returns a collection of value objects (0-n)
etc.

In your case you would have a ProductDAO that has something like the above methods. This ProductDAO would then return ProductVO's and collections of them.

Data Access Objects can also return Business Objects (BO) which may contain multiple VO's and additional methods that are business case specific.

Addendum: In your controller you call a ProductDAO to find the products you want. The returned ProductVO(s) are then passed to the view (as request attributes in Java). The view then loops through/displays the data from the productVO's.