MVC Question: The Model

Hi all,

I’m fairly new to PHP (about a year-and-a-quarter of experience with coding PHP, or coding at all), quite new to the concept of MVC and OOP (about 5 months ago I really started looking into these, haven’t executed an official ‘project’ with them yet but done plenty of hobby-coding with them), and VERY new to Yii itself (about two weeks-ish?). I was mainly using CodeIgniter for my personal coding before now but I’ve recently been hired at a new job that primarily uses Yii, so I’m experimenting with it and trying to get myself up to a reasonable speed.

Sadly it seems uncertain if I’ll be able to do that, since I’ve come to the conclusion that I may not entirely understand MVC as a concept, let alone execute it in a professional environment.

See, when I started working with CodeIgniter and MVC, I always read the ‘Model’ portion of that equation as ‘the data’, which to my largely-inline-PHP mind meant: ‘the database’. So I assumed - perhaps foolishly - that the Model’s job was to work with the database and pass information back to the Controller. However, as I was reading through Yii’s documentation, the example Yii gave of a Model had to do with a contact form, and expressing the fields of the contact form as an array of values.

I’ll be honest; I’ve read that documentation and have read other works as well, and I’m really struggling to understand the Model. It seems, as a concept, to be far more abstract an idea than the Controller or View. Most of what I read says only, or in essence, that it ‘represents the data and does not depend on the View or Controller’. I might just be super-junior at this, but that… doesn’t really explain to me what it should actually be DOING.

Is anyone able to maybe give me a run-down, as though you’re talking to an idiot (because I am!) of what the Model’s role is in all this?

The model represents your data but it can also "do stuff". It is not just a database, it also has methods/functions.

You might have an "Invoice" class, that represents an "invoices" table in your database. But your class not only can give you the data, it can also perform actions like calculating a total.

When talking about the model, see it as a representation of the real world. Whatever your application deals with, it is represented in your classes. If your application deals with invoices, customers and items, then these "entities" will be represented by classes in your model.

Think of a model train: It is is simplified (and much smaller) representation of the real world. And that’s also what the model in your application should be.

Here’s the draft I’ve put together recently: https://github.com/samdark/yii2-cookbook/blob/master/book/mvc.md