In MVC, should the Model or the Controller be processing and parsing data? - codeigniter

Until now, in my MVC application, I've been using the Model mainly just to access the database, and very little else. I've always looked on the Controller as the true brains of the operation. But I'm not sure if I've been correctly utilizing the MVC model.
For example, assume a database of financial transactions (order number, order items, amount, customer info, etc.). Now, assume there is a function to process a .csv file, and return it as an array, to be inserted into the database of transactions.
I've placed my .csv parse function in my Controller, then the controller passes the parsed information to a function in the Model to be inserted. However, strictly speaking, should the .csv parsing function be included in the Model instead?
EDIT: For clarity's sake, I specifically am using CodeIgniter, however the question does pertain to MVC structure in general.

The internet is full of discussion about what is true MVC. This answer is from the perspective of the CodeIgniter (CI) implementation of MVC. Read the official line here.
As it says on the linked page "CodeIgniter has a fairly loose approach to MVC...". Which, IMO, means there aren't any truly wrong ways to do things. That said, the MVC pattern is a pretty good way to achieve Separation of Concerns (SoC) (defined here). CI will allow you to follow the MVC pattern while, as the linked documentation page says, "...enabling you to work in a way that makes the most sense to you."
Models need not be restricted to database functions. (Though if that makes sense to you, then by all means, do it.) Many CI developers put all kinds of "business logic" in Models. Often this logic could just as easily reside in a custom library. I've often had cases where that "business logic" is so trivial it makes perfect sense to have it in a Controller. So, strictly speaking - there really isn't any strictly speaking.
In your case, and as one of the comments suggests, it might make sense to put the CSV functionality into a library (a.k.a. service). That makes it easy to use in multiple places - either Controller or Model.
Ultimately you want to keep any given block of code relevant to, and only to, the task at hand. Hopefully this can be done in a way that keeps the code DRY (Don't Repeat Yourself). It's up to you to determine how to achieve the desired end result.
You get to decide what the terms Model, View, and Controller mean.

As a general rule MVC is popular because it supports separation of concerns, which is a core tenet of SOLID programming. Speaking generically (different flavors support/ recommend different implementations), your model holds your data (and often metadata for how to validate or parse), your view renders your data, and your controller manages the flow of your data (this is also usually where security and validation occur).
In most systems, the Single Responsibility Principle would suggest that while business logic must occur at the controller level, it shouldn't actually occur in the controller class. Typically, business logic is done in a service, usually injected into the controller. The controller invokes the service with data from the model, gets a result that goes into the model (or a different model), and invokes the view to render it.
So in answer to your question, following "best practices" (and I'll put that in quotes because there's a lot of opinions out there and it's not a black and white proposition), your controller should not be processing and parsing data, and neither should your model; it should be invoking the service that processes and parses the data, then returning the results of aforementioned invocation.
Now... is it necessary to do that in a service? No. You may find it more appropriate, given the size and complexity of your application (i.e. small and not requiring regular maintenance and updates) to take some shortcuts and put the business logic into the controller or the model; it's not like it won't work. If you are following or intend to follow the intent of the Separation of Concerns and SOLID principles, however (and it's a good idea on larger, more complex projects), it's best to refactor that out.

Back to the old concept of decomposing the project logic as Models and Business Logic and the Data Access Layer.
Models was the very thin layer to represent the objects
Business Logic layer was for validations and calling the methods and for processing the data
Data Access Layer for connecting the database and to provide the OR relation
in the MVC, and taking asp.net/tutorials as reference:
Models : to store all the object structure
View: is like an engine to display the data was sent from the controller ( you can think about the view as the xsl file of the xml which is models in this case)
Controller: the place where you call the methods and to execute the processes.
usually you can extend the models to support the validations
finally, in my opinion and based on my experience, most of the sensitive processes that take some execution time, I code it on the sql server side for better performance, and easy to update the procedures in case if any rule was injected or some adjustments was required, all mentioned can be done without rebuilding your application.
I hope my answer gives you some hints and to help you

If your CSV processing is used in more than one place, you can use a CI library to store the processing function. Or you can create a CSV model to store the processing function. That is up to you. I would initially code this in the controller, then if needed again elsewhere, that is when I would factor it out into a library.
Traditionally, models interact with the database, controllers deal with the incoming request, how to process it, what view to respond with. That leaves a layer of business logic (for instance your CSV processing) which I would put in a library, but many would put in its own model.
There is no hard rule about this. MVC, however it was initially proposed, is a loose term interpreted differently in different environments.
Personally, with CI, I use thin controllers, fat models that also contain business logic, and processing logic like CSV parsing I would put in a library, for ease of reuse between projects.

Related

Understanding the model in MVC.

I've worked with OOP for a while now, and have gotten into the habit of creating classes for 'things', such as person, account, etc. I was coding in Java for this.
Recently I begun to work with MVC (in PHP), and I've come to realise that, contrary to what I originally thought, the model is not like an OOP class - feel free to correct me if I'm wrong, but my understanding is that the model is simply an interface between the controller and the database (maybe with data processing - more on this below). My reason for thinking this stems from my recent messing around with the CodeIgniter framework for PHP. CI doesn't allow for instances of models. Rather, it's a singleton pattern, and in most tutorials I've seen, it's used only for database queries and sometimes some static method.
Now, coming from OOP, I've gotten into the habit of having classes where the data is stored and able to be manipulated (an OOP class). My issue is that in MVC, I'm not sure where this takes place, if it does (I initially thought 'class' was synonymous with 'model'). So, I guess what I'm looking for is someone to explain to me:
Where does the manipulation of data (business logic) take place? I've read many articles and posts, and it seems some prefer to do it in the controller, and others in the model. Is one of these more correct than the other in terms of MVC?
Where/how do I store data for use within my application, such as that from a database or JSON/XML files returned from an API call? I'm talking things that would usually be attributes in an OOP class. Does this even still take place, or is it straight from the database to the view without being stored in variables in a class?
If you could link me to any guides/sites that may help me to understand this all better, I would appreciate it.
Representing MVC in terms of classes, you can say that:
Model - A class which stores/provides data.
View - A class which provides functionality to display the provided data in a particular fashion.
Controller - A class which controls that how the data is manipulated and passed around.
MVC design is adopted to provide facility to easily replace any of the module (Model/View/Controller) without affecting the other. In most cases, it is the view which gets changed (like same data represented in form of graphs, chats) but other modules must also be made independent of others.
This is an interesting question, and you often hear contrary things about how clean and stripped down models should be vs them actually doing everything you'd think they should do. If I were you I'd take a look at data mappers. Tons of people much smarter than I have written on the subject, so please do some research, but I'll see if I can summarize.
The idea is that you separate out your concept of a model into two things. The first is the standard model. This simple becomes a property bag. All it does is have a state that often reflects your database data, or what your database data will be once saved, or however you use it.
The second is a data mapper. This is where you put the heavy-lifting stuff. It's job becomes providing a layer between your pure model, and the database, that's it. It talks to the database, retrieves data specific to your model, and maps it to the model. Or it reads the model, and writes that data to the database. Or it compares the model's data with that of the DB.
What this does is it allows each layer to concern itself with only one thing. The model only has to keep a state, and be aware of its state. Or have some functionality related to the model that does not involve the database or storage. Now the model no longer cares about talking to the database which is hugely freeing! Now if you ever switch to a different database, or you switch to cookies or storing things in files or caching or any other form of persistence, you never need to change your models. All you have to change is the mapping layer that communicates between your models and the DB.

How to think about Controllers in angularjs

I'm scratching the surface with Angularjs, and thought I'd run a conceptual question past the fine folks of SO. This is a newbie question from a seasoned developer.
The application has dashboard requirements... a single page that surfaces stuff from many parts of the application. Different user types get different dashboards. We already have a legacy back end, so the first task is to build the dashboard to show many bits from it's new RESTful service layer.
I'm wondering how I should conceptually think about the controllers needed to support this?
The first question is... should they be model-centric or view-centric? In other words, should they be "view-centric" controllers that have the word "Dashboard" in them? Or should they be more focused on the model elements they represent, like "Tasks", "Contacts", "Notifications". Or should there be both where the dashboard controllers work with model-centric controllers?
The next question is... what level of granularity should the controllers represent? If view-centric "Dashboards" controllers, should they be "ManagerDashboardController" and "WorkerDashboardController"? If model-centric controllers, should there be controllers such as "LateTasks" & "OnTimeTasks" since I need to display them on different sections of the dashboard, with slightly different data?
I'm looking for tangible advice based on real-world experience and/or references to great links I've yet to find.
Here are my views from developing business applications in Angular for the past 6 months:
Role of a Controller
Initialization (loading initial data, setting options)
Exposing variables and functions to the template through the $scope
Application flow (through exposure of functions that can change state, or $watches)
I have found that, much like in traditional MVC frameworks, the controllers in an Angular app should really be super slim. Little if any business logic should be in the controllers, and should be instead be encapsulated in your models. I came to this conclusion after hearing the follow line from a presentation by Miško Hevery: "the purpose of the scope is to refer to the model and not be the model." That was the most valuable and enlightening line I got from that presentation (though I recommend to watch the whole video); that line directly resulted in me slimming down my controllers by almost 50%-70%.
For example, my company has a concept of an Order. I created a model that encapsulated all the properties of this business object, as well as its behaviours and injected them into the controllers. One business rule we had was the ability to add a Booking (another business object) to the Order. Originally in my controller, I had a $scope.addBooking function that first created a new Booking, then took the order and did a $scope.order.bookings.push(newBooking). Instead, I moved this business logic (addBooking function) directly into my Order model, and in the template I could then do something like <button ng-click="order.addBooking()">Add Booking</button> without adding a single line of code into my controller.
A lot of the code I put in my controllers when I was first starting off with angular, I found could be stripped out and placed either in my models, directives, or services (mostly the first two in my case). The remainder of the code left in my controllers almost all fell into one of the above 3 roles I listed above. It was either initialization code (e.g. firing an AJAX request to fetch data of the relevant business objects), scope assignment of objects, or scope assignment of functions that dealt with application flow (e.g. $scope.save or $scope.cancel that might send you back to a different page).
Should controllers be model-centric or view-centric?
This is an interesting question, one that I haven't thought about before. When I hear view-centric, I think of a controller that deals primarily with the view and how things are displayed. I feel there shouldn't be any controllers that are purely view-centric, the reason being it seems a view-centric controller can probably be transformed into a directive. You mentioned view-centric controllers as being like a Dashboard controller, which sounds like something that could definitely be made into a generic directive. Your directives should encapsulate most of your view logic, while your controllers focus on simply exposing your models to the view for consumption (back to the role of the controller). This has me thinking that controllers should more often be model-centric.
I think really the only conclusion I can come to is if a controller starts becoming too view-centric (with many variables and functions that deal primarily with the view and UI behaviour) then that is a sign that parts of your controller can be pulled out into a directive, making your controller slimmer.
This is very subjective but here is my answer to your questions
should controllers be model-centric or view-centric?
It depends (as always), I always try to have small controllers for the different parts of the page.
Some parts of the page are very view-centric (typically the ones that are shared among the different views). I usually have a menuCtrl, a headerCtrl and footerCtrl. This ctrls are very coupled to those parts of the page so a make them view-centric.
The other parts of the view, the ones that are business related are much more coupled to the business rules and in extension to the model so I make those ctrls model-centric. On an account´s business app, I would probably have an accountCtrl, an ownerCtrl, and so on. By doing so I can reuse them on different views if needed (and are much easier to test)
what level of granularity should the controllers represent?
The smallest as possible. Try to have small controllers that prepare the model for different parts of the page. If you have a big controller it will be hard to test, maintain and you will probably be forced to duplicate code on different parts of your application.
advices and recomentations with controllers
Keep them small.
Avoid DOM manipulation inside of them (use directives instead).
Use the controllers just to prepare the model. whenever possible delegate all the logic of your app to services. If you do so, it won´t really matter that much if your controller is view-centric or model-centric.
As I said before this is a very subjective matter and I´m sure many people will disagree with me.
I hope this could help you.
Basic Idea
So I'm actually in the process of migrating a legacy code base over to a restful based web service architecture utilizing AngularJs
Controllers are responsible for managing the data that is consumed by the view aka the webpage. My personal preference is that there is a one to one relationship between the controller and the view that it is serving. So, based on the question, Angular controllers should be more view centric. I'm sure that there are plenty of people who will disagree with me though.
If you are worried about the extensibility of this pattern, you should place your business logic and data access within Angular Services as described here. This offers you a tremendous amount of reuse of business logic operations as well as unit testability.
TLDR;
The specifications for Angular are changing all the time and with each new version there will be a new standard. A more view centric architecture looks appropriate for this application.
For some more complete reading on the subject I recommend checking out:
3 Tips To Building Enterprise Grade Angular/Node Applications
Lessons Learned: A Year with a Large AngularJS Project

What are your best practices when using an MVC-based web framework?

A few general questions to those who are well-versed in developing web-based applications.
Question 1:
How do you avoid the problem of "dependency carrying"? From what I understand, the first point of object retrieval should happen in your controller's action method. From there, you can use a variety of models, classes, services, and components that can require certain objects.
How do you avoid the need to pass an object to another just because an object it uses requires it? I'd like to avoid going to the database/cache to get the data again, but I also don't want to create functions that require a ton of parameters. Should the controller action be the place where you create every object that you'll eventually need for the request?
Question 2:
What data do you store in the session? My understanding is that you should generally only store things like user id, email address, name, and access permissions.
What if you have data that needs to be analyzed for every request when a user is logged in? Should you store the entire user object in the cache versus the session?
Question 3:
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model? What are the advantages to this approach?
Question 4:
If your site is driven by a user id, how do you unit test your code base? Is this why you should have all of your data-retrieval methods in a centralized place so you can override it in your unit tests?
Question 5:
Generally speaking, do you unit test your controllers? I have heard many say that it's a difficult and even a bad practice. What is your opinion of it? What exactly do you test within your controllers?
Any other tidbits of information that you'd like to share regarding best practices are welcome! I'm always willing to learn more.
How do you avoid the problem of "dependency carrying"?
Good object oriented design of a BaseController SuperClass can handle a lot of the heavy lifting of instantiating commonly used objects etc. Usage of Composite types to share data across calls is a not so uncommon practice. E.g. creating some Context Object unique to your application within the Controller to share information among processes isn't a terrible idea.
What data do you store in the session?
As few things as is humanly possible.
If there is some data intensive operation which requires a lot of overhead to process AND it's required quite often by the application, it is a suitable candidate for session storage. And yes, storage of information such as User Id and other personalization information is not a bad practice for session state. Generally though the usage of cookies is the preferred method for personalization. Always remember though to never, ever, trust the content of cookies e.g. properly validate what's read before trusting it.
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model?
I prefer to use the Repository pattern for my models. The model itself usually contains simple business rule validations etc while the Repository hits a Business Object for results and transformations/manipulations. There are a lot of Patterns and ORM tools out in the market and this is a heavily debated topic so it sometimes just comes down to familiarity with tools etc...
What are the advantages to this approach?
The advantage I see with the Repository Pattern is the dumber your models are, the easier they are to modify. If they are representatives of a Business Object (such as a web service or data table), changes to those underlying objects is sufficiently abstracted from the presentation logic that is my MVC application. If I implement all the logic to load the model within the model itself, I am kind of violating a separation of concerns pattern. Again though, this is all very subjective.
If your site is driven by a user id, how do you unit test your code base?
It is highly advised to use Dependency Injection whenever possible in code. Some IoC Containers take care of this rather efficiently and once understood greatly improve your overall architecture and design. That being said, the user context itself should be implemented via some form of known interface that can then be "mocked" in your application. You can then, in your test harness, mock any user you wish and all dependent objects won't know the difference because they will be simply looking at an interface.
Generally speaking, do you unit test your controllers?
Absolutely. Since controllers are expected to return known content-types, with the proper testing tools we can use practices to mock the HttpContext information, call the Action Method and view the results to see they match our expectations. Sometimes this results in looking only for HTTP status codes when the result is some massive HTML document, but in the cases of a JSON response we can readily see that the action method is returning all scenario's information as expected
What exactly do you test within your controllers?
Any and all publicly declared members of your controller should be tested thoroughly.
Long question, longer answer. Hope this helps anyone and please just take this all as my own opinion. A lot of these questions are religious debates and you're always safe just practicing proper Object Oriented Design, SOLID, Interface Programming, DRY etc...
Regarding dependency explosion, the book Dependency Injection in .NET (which is excellent) explains that too many dependencies reveals that your controller is taking on too much responsibility, i.e. is violating the single responsibility principle. Some of that responsibility should be abstracted behind aggregates that perform multiple operations.
Basically, your controller should be dumb. If it needs that many dependencies to do its job, it's doing too much! It should just take user input (e.g. URLs, query strings, or POST data) and pass along that data, in the appropriate format, to your service layer.
Example, drawn from the book
We start with an OrderService with dependencies on OrderRepository, IMessageService, IBillingSystem, IInventoryManagement, and ILocationService. It's not a controller, but the same principle applies.
We notice that ILocationService and IInventoryManagement are both really implementation details of an order fulfillment algorithm (use the location service to find the closest warehouse, then manage its inventory). So we abstract them into IOrderFulfillment, and a concrete implementation LocationOrderFulfillment that uses IInventoryManagement and ILocationService. This is cool, because we have hidden some details away from our OrderService and furthermore brought to light an important domain concept: order fulfillment. We could implement this domain concept in a non-location-based way now, without having to change OrderService, since it only depends on the interface.
Next we notice that IMessageService, IBillingSystem, and our new IOrderFulfillment abstractions are all really used in the same way: they are notified about the order. So we create an INotificationService, and make MessageNotification a concrete implementation of both INotificationService and IMessageService. Similarly for BillingNotification and OrderFulfillmentNotification.
Now here's the trick: we create a new CompositeNotificationService, which derives from INotificationService and delegates to various "child" INotificationService instances. The concrete instance we use to solve our original problem will delegate in particular to MessageNotification, BillingNotification, and OrderFulfillmentNotification. But if we wish to notify more systems, we don' have to go edit our controller: we just have to implement our particular CompositeNotificationService differently.
Our OrderService now depends only on OrderRepository and INotificationService, which is much more reasonable! It has two constructor parameters instead of 5, and most importantly, it takes on almost no responsibility for figuring out what to do.

What is the usage of Model in MVC? Is it actually useful?

I'm new in this, so bear with me. I've been using one MVC framework in a couple of projects lately, and after a while, I'm disillusioned in the perceived usefulness of the 'Model' in MVC.
I get the usefulness of Controllers and Views, I know that separation between presentation and logic is important to make the code more maintainable in the future, although not necessarily faster or more robust.
If all logic should be placed inside the controller in the first place, I don't see any use for Model, especially the Active-Record. We already have a language that is so robust and easy to use to communicate with the database, am I right? It's called SQL. For me when models are implemented like active-record, it's usefulness depends on whether or not you want your app to fit in multiple databases.
So what I'm asking is, if you're only using one database, why bother with Models and Active-Records? Why don't just use SQL? Why the extra layer of complexity? Do you guys have any case studies/real-life stories where models actually can do things better than just using the database class and SQL-away?
Again, I'm sorry if I seem to be so ignorant, but I really don't know why Models are important. Thanks for answering.
First, you are assuming that a model layer necessarily uses some kind of ORM, in order to abstract SQL away. This is not true: you may create a model layer which is loosely-coupled from the Controller layer but tightly-coupled to a particular DBMS, and so avoid using a full-featured ORM.
There are some ORM libraries, like Hibernate (Java), NHibernate (.NET), Doctrine (PHP) or ActiveRecord-Rails (Ruby) that really can generate all actual SQL statements for you; but if you think ORM is unnecessary, and you want to define all SQL statements by hand, don't use them.
Still, IMHO this does NOT mean you should just place all you DB related logic inside the controller layer. This is called the "fat controller" approach, and it is a road that leads, many times, to bloated, unmaintainable code. You could use it for simple CRUD projects, but anything beyond that will demand the existence of a real "Model".
You seem to care about MVC. Please, read also something about TDD. A wise man once said "legacy code is code without tests". When you learn that automated unit tests are as important as the "real" code, you will understand why there are so many layers in an enterprise application, and why your Model layer should be separate from the Controller. A block of code that tries to do everything (presentation, business logic, data persistence) simply cannot be easily tested (nor debugged by the way).
Edit
"Model" is a little bit fuzzy term. Depending from where you look at, it can mean something slightly different. For instance, PHP e Ruby programmers frequently use it as a synonym to an Active Record, which is not accurate. Some other developers seem to believe that a "model" is just some kind of DTO, which is also not right.
I rather use the definition of model as seen in Wikipedia:
The central component of MVC, the model, captures the application's behavior in terms of its problem domain, independent of the user interface. The model directly manages the application's data, logic and rules.
So the Model is the biggest, most important layer in most MVC applications. That's why it is usually divided in sub-layers: Domain, Service, Data Access and so on. The Model is usually exposed through the Domain, because it's there where you'll find the methods that your controller will call. But the Data Access layer belongs to the "Model" too. Anything that is related to data persistence and business logic belongs to it.
In most real-life situations, data that comes from the user doesn't go straight into the database.
It must often be validated, filtered, or transformed.
The role of the model layer is usually to make sure that data arrives properly into the backend store (usually the database) by performing these operations, which should not be the responsibility of the controller (skinny controller, fat model), and not the responsibility of the database engine itself.
In other words, the Model layer is responsible - or `knows' - how the data should be handled.
Most modern MVC frameworks provide ways to specify contracts over the data validity requirements, such as Rails.
Here's an example from http://biodegradablegeek.com/2008/02/introduction-to-validations-validation-error-handling-in-rails/:
class Cat
validates_inclusion_of :sex, :in => %w(M F), :message => 'must be M or F'
validates_inclusion_of :vaccinated, :in => [true,false]
validates_inclusion_of :fiv, :in => [true,false]
validates_inclusion_of :age, :within => 1..30
validates_each :weight do |record, attr, value|
record.errors.add attr, 'should be a minimum of 1 pound' if value and value /^[01][0-9]\/[0-9]{2}\/[0-9]{4}$/
validates_length_of :comment, :allow_blank => true, :allow_nil => true, :maximum => 500
end
Here, several of the data validity requirements cannot be handled by the database, and should not be handled in controllers, because any modification in those requirements might break the code in several places.
Therefore, the model is the best place to make sure data is coherent for your domain.
There's a lot more to be said about it, but I felt like tackling a point that seems important to me, motivated by practical experience :)
It's not an ignorant question at all! Just the fact that you're asking it instead of simply ignoring the whole MVC theory and doing as you please is nice. :-)
To answer your question: conceptually, Models simply provide a nice abstraction for your data. Instead of thinking in terms of "how do I write this inner join to get all the fields I need", models enable you to think in terms of "how are my application's objects related to each other, how do they interact and how can I get the data I need from them".
In the same way that Views and Controllers help you seperate presentation from logic, Models help you seperate the application's logic (from a user's perspective, anyway) from the gritty details as to where your data actually comes from and how it's represented internally.
To give a more specific example (if not completely realistic): in theory, you could write your whole application in a way you fetched all the data through SQL queries. But later you realized you wanted to use some noSQL (CouchDB, etc) engine because you needed horizontal scaling.
With models (and a framework that can use both types of storage, of course :-)) you wouldn't have to worry about the details, as all your important data is already represented in a generic manner through your models and both views and controllers can act upon that representation.
Without them, you'd probably have to rewrite a large chunk of code just to adapt your data fetching to the new backend.
And that's just on the boring storage part. With pure SQL, it's much harder to define the interactions between your application's objects (i.e. the business logic) because you just won't do that in SQL (probably, anyway).
It's not a perfect explanation (far from it), but I hope it helps.
The models should contain all your logic. The controller is only responsible with logic related to user interaction. All the domain-related functionality (what's known as "business logic") should be placed in the model and decoupled from controller code. Like this you can achieve a better separation of concerns and code reusability.
For example, let's say you are writing an application to let users enter information about themselfs and receive diet recomandations.
One the one hand, you would put code related to transforming user provided data into a list of diet recomandations in the model part. This includes database access, but also any calculations , algorithms and processing related to the problem in question (the problem domain).
On the other hand, you put the code to log the users in, show a form, gather the form data, validate it, in the controller. This way for instance you could later add an api to your app (which uses different code for authentication, getting data from the user, validation etc.) and reuse the code to generate the results (from the model).
This is just an example of what the model is good for.
I always relate Model to data irrespective of where it is present or how it is represented. In MVC V displays data and C handles change. Even if you have all the data to be presented on the screen in a HashMap inside your controller; that HashMap will be called the Model.

MVC Architecture. Whats in a model?

I am new to MVC but I can already see its benefits and advantages. However, I have a (probably easy to answer) design question:
I have been thinking about models and debating the proper way to structure them. The way I see it there are a few options:
1) Models and table structure have a 1 to 1 relationship...meaning that pretty much for every table there is a corresponding model. The model class has attributes corresponding to the table columns and has whatever methods that are needed (like getters and setters) to manipulate data in the table in whatever way is necessary. This seems like the generic option and I guess I would then have the controller call the models as necessary to perform whatever business function is necessary.
2) Models are tied more closely to the operation of the business logic rather than the data: so for example if on the front end a deletion of a certain object affects multiple tables, the model then 'models' this behavior and interacts with several tables and performs the necessary function. The controller then simply needs to call a single model for whatever business behavior is desired. This is less generic since the models are much more tightly coupled..but seems quicker to implement.
3) Something in between the first 2 options. Or maybe I am completely missing the point.
Hopefully this makes sense! If I am not totally missing the point, I am inclined to think that option (1) is better. Any idea?
Edit: Not that it should matter, but I plan on using Codeigniter PHP MVC framework.
Both are valid implementations, and, depending on your needs, can work well.
Your #1 is essentially describing the Active Record pattern, which is used by SubSonic, Castle, and lots of other ORM implementations.
Your #2 is essentially describing the Entity Framework/Hibernate/LightSpeed approach, where you are dealing with objects that are more conceptually related to your domain rather than to tables. Instead of your objects containing foreign key ID properties, they actually contain the other domain object references, which are then instantiated in an on-access basis.
Both ways are great. The Active Record approach is usually more intuitive for beginners and has potentially less pitfalls. EF-style can save a lot of base-level coding and dealing with FK's directly in code.
Edit: To be clear, what you describe in both situations is data access layer related, rather then strictly model related. However in reality you're pretty close, as most models tend to simply represent one or more of these types of objects.
All of the above.
The approach you use depends on your design philosophy. If you prefer to design your application using business domains and drive that into the database design, then you favor the second approach. If you prefer to build your database first, and then create model classes from the database schema, then you favor the first approach. Both methods are valid ways to build software.
Number 1 is the way to go. Option 2 is really the controller's job. For example, the controller then takes the models and performs actions on them, and passes the results to the view.
Think of it this way:
Model = your data
Controller = business logic
View = display of data and actions
This is highly simplistic, but it's how I picture it in my mind when I go to design a system.
Think of the database as the Model, the business logic as the Controller, and the UI as the View. That may help. It's an overly simplified approach to things, but it gets the data / behavior separation roughly correct.
I don't think it has to be an either/or situation. Your first point is what would be called a Model, but your 2nd point sounds like a View Model, which is most often a composition of various Models and parts of Models that will be sent to the view. The controller is responsible for doing that composition and potentially decomposition when information is sent back from the View.

Resources