• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Models, where, when and why?

#1
Question 
Hello all,

I've been using CI for a while now, but have the slight suspicion I'm missing the point about models. I've never used them. Now I'm starting a new project, and want to make sure I should or shouldn't use them.

I know what the VC part in MVC stands for. Views show things, Controllers make sure the views have something to work with. But what do Models do?

My point is, what can Models do that I can't achieve with a library? Up to now, I've been using libraries as CI-replacement for classes, which I used when I programmed Object Oriented PHP without framework. This has been going well, no issues there. But I've also read somewhere that libraries are mostly used for classes that can be used for multiple projects, like an email class or something. Is it a class which is related to a specific project, you should use a Model.

But in other threads and documentation, Models are only used for database-related tasks (which is fairly close to what a Model should do, judging by the definition of a Model in an MVC). So get, insert, update, delete kind of thing. For instance, getting the contents of a blogpost could be done by using
PHP Code:
$blog->get_post_by_id(24
.

Then this is usually returned as a basic result, using
Code:
$query->result();

This gives you an array with the contents of that blog-post, which you can pass through your Controller to the View in which it is outputted. But it isn't stored in an object of a class, so apart from passing it through, there's nothing you can do with it.

Does that mean that I should have a Model and a library for the same blogpost? So that my Controller creates an object from a library, and that library loads the corresponding Model? Then the library calls upon the Model to get the data from the database, which is then stored in the library-object, which is used by the Controller to pass through to the View? Doesn't that mean double work, having to create nearly identical versions of a blog-post, both as a Model and a library?

So yes, I'm confused. Online I can't find a proper answer to my confusion. With the start of a new forum here, I though someone would be inclined to either point me (and future candidates) to the right direction, or elaborate themselves.

Thanks in advance!
Reply

#2
In most of our programms, the model is that what your appliction is. On database driven applications it is the data from the db in other way the filesystem or the memory. Models should/could also used for logic stuff like filtering, calculation, data validations etc. and the controller gets only the maintained data back.

E.g. if you have some calculation stuff you calculation the output inside the model and route it to the controller. No the calculation logic should be changed you only have to change the logic inside the model.

So for me the model for that design pattern is a layer between the application and the data and always god practice to get your code maintable.

BTW: I think this was the first paper to MVC : http://heim.ifi.uio.no/~trygver/themes/m...index.html

(10-24-2014, 12:03 AM)Thyrosis Wrote: Does that mean that I should have a Model and a library for the same blogpost? So that my Controller creates an object from a library, and that library loads the corresponding Model? Then the library calls upon the Model to get the data from the database, which is then stored in the library-object, which is used by the Controller to pass through to the View? Doesn't that mean double work, having to create nearly identical versions of a blog-post, both as a Model and a library?

In your case i think it depends on your taste. in the blogpost example you can do all of the logic with controller methods, than of course with the model. If i program a library (class) for some stuff i would design it with all of the needed logic and dependences even the datastuff (file, db, etc.) so no models are needed.

So you dont have to use M in MVC but its the goal of this pattern .... and every pattern is only a proposal. But if you use one you should work with it as it is scheduled, so other programmers can easy work with it.

Reply

#3
My two cents (as I've been having some "completely redesign the application" thoughts this morning)... And spent some time reading about "design patterns".

Compared to you, Thyrosis, I don't use many libraries in a project, (mostly) just for stuff, that I really now I will reuse and is application independent - like email, ACL for user based applications (as I use my own), for example a "config" library (used for user changeable configuration)...

And as far as I understand (correct me if i'm wrong), basic MVC pattern is a "funny" beast, as it is pretty old (before the web, modern applications...), so the M is nowadays not used just for data retrieval but for a lot more.

I use the CI Model in this way:
- To retrieve the data and return it to the controllers
- To manipulate/change/convert the data so it's usage is simple later on
- To check consistency or "logic" like so: "if row X in A does not exist, do not insert into row X into B" or "if X exists then update Z,Y,W" and at the same time (where constraints are not set in the DB) to check and keep consistency of data
- And in some cases, I call some library's methods and functions to again, return data which can be simply used in controllers (and later, views).
- I do try to keep controllers as slim(er) Smile (but when I started with CI, this was not the case, I did everything in controllers and used models exclusively for data retrieval)

I have to say, your approach, using mainly libraries, has some benefits...
Anyways, as for the libraries, I second Rufnex - they should be written in a way, that they are depended only on "themselves", so no models needed...
Reply

#4
If you find yourself using the same database methods etc; over and over then it is a good time to create a MY_Model and place these methods in it.

Then when you create any new model you just extend it from your MY_Model. ( DRY ).

The MY_Model goes into ./application/core/MY_Model.php
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#5
To me, the point of the model is to hold the business logic of the data. That includes getting the data from the database, and then ensuring that any application-specific processing is done there also. Like if you need to ensure that post titles are always ucwords you could enforce that in the model. (Yes, that's a fairly silly example...)

The model allows all data to be treated the same, no matter where you use it at. If you use it from a library or controller, the business rules/logic are enforced. All in a single place that helps remove the possibility for error.

It sounds like you are using a library to do that exact same thing. So, in your case, I believe it's a matter of terminology. Your library is what I would use a model for. I think model is the more traditional place for it.

To help with testing your applications, it is definitely better to keep your Controller functioning as just a little guy that sits around directing traffic and keep it as "thin" as possible.
Reply

#6
I think models are best treated as a black-box written by third-parties.

From the View a user requests certain information which is Routed to the relevant Controller. The request is then sent directly to the Model.

The Model's task is to sanitize and interpret the request then return data in a specific agreed format. The returned data could even be Null or an empty array.

Controller just accepts the Model's data, makes absolutely no tests and/or changes and just passes the Model's data to the View.

Before I forget!
When returning data from a Model (also applies to Controllers and Libraries) it is tempting to Html format the data with size, bold, colours, etc. This is remarkably easy and seems such a good idea at the time but later becomes an onerous task to make changes to the View. It becomes necessary to sift through reams of Controller, Library of Model's script to find the offending output which is creating the View havoc!

The time saved by formatting in the wrong place is less than negligible and even lesser if the data is cached Smile

I have the T-shirts!!!
Reply

#7
Thanks to all for the replies. I think I can safely assume that even here there is no "should" and "shouldn't" and that it is a matter of personal preference or company policy.

(10-24-2014, 08:17 AM)kilishan Wrote: To me, the point of the model is to hold the business logic of the data. That includes getting the data from the database, and then ensuring that any application-specific processing is done there also. Like if you need to ensure that post titles are always ucwords you could enforce that in the model. (Yes, that's a fairly silly example...)

No, that's no silly example at all. It is things like those that got me confused in the first place. Because uppercasing the post-title has nothing to do with the database, it's the title of a post (an object in my opinion). I would expect functionality like that in a library, not in a Model.

Think about this one. I have two classes. User and Post. A Post is made by a User. So in the post-table, a field 'user' is active, which holds the userid of the User who posted the Post.

But, when I pull up the Post to use in a View, I don't want Post->user to hold the userID, I want it to hold a User. So Post->User->name will give me the username.

Also, I have a class Category. A Post belongs to a Category. So under Post->category I don't want to see the categoryID, but I want it to hold a Category object.

I think I'm gonna stick with using libraries to work situations like that, but just for the sake of clarity: how would I go about that using Models? Can you have Model include a Model like this?

John_Betong Wrote:When returning data from a Model (also applies to Controllers and Libraries) it is tempting to Html format the data with size, bold, colours, etc. This is remarkably easy and seems such a good idea at the time but later becomes an onerous task to make changes to the View. It becomes necessary to sift through reams of Controller, Library of Model's script to find the offending output which is creating the View havoc!

Yeah, I figured that one out long time ago... The hard way. I'm guessing a lot of devs experienced this first hand too Big Grin
Reply

#8
ok, seriously, don't do that. You might as well not use a framework at all and just do procedural PHP. That's what you're doing anyway.

You are correct when you say that your controllers send the information to your views. But where do they get this information?
They get if from the models. Your models is where all your business logic is placed.

All the interaction with your database(s) is done these. All the processing of your objects and data is done there. The controller should only get the info from there and send it to the views, nothing else.

If you have skinny models and fat controllers you're probably doing it wrong. Your Models should be fat and your controllers skinny. =)
Reply

#9
as marcogmonteiro said, what your doing is not using the framework for what it was built to do.

Controllers should never access your database(s) directly.
Views should never access your database(s) directly.
Libraries should never access your database(s) directly.

This is what the Models are for. they perform CRUD operations on your data source(s).

Controllers should always be your skinniest part of your application.

Other wise your breaking the MVC pattern and might as well not be using a framework at all.
Reply

#10
I tend to agree with Hobbes. Part of what I try to get through to my students is proper separation of concerns. Controllers are for handling usecases, models encapsulate data sources, and views present stuff for human consumption. Taken to an extreme, we end up with a Model-View-Adapter pattern, where the view has no idea where data comes from - that is up to the controller.

I give my students a small set of "golden rules" at the beginning of my course...

If a model generates HTML, you are "fired".
If a view is aware of the origin of data (eg RDB), you are "fired".

In this context, "fired" means 20% off your grade for a lab or assignment, no questions and no mercy. You also get "fired" if your webapp somehow triggers a PHP error visible to the user.

This is a simplisitic view, and doesn't work or apply in absolutely every case, granted, but it sure drives home the point of MVC Big Grin
James Parry
Project Lead
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.