how to use codeigniter database models - codeigniter

I am wondering how the models in code ignitor are suposed to be used.
Lets say I have a couple of tables in menu items database, and I want to query information for each table in different controllers. Do I make different model classes for each of the tables and layout the functions within them?
Thanks!

Models should contain all the functionality for retrieving and inserting data into your database. A controller will load a model:
$this->load->model('model_name');
The controller then fetches any data needed by the view through the abstract functions defined in your model.
It would be best to create a different model for each table although its is not essential.
You should read up about the MVC design pattern, it is used by codeigniter and many other frameworks because it is efficient and allows code reuse. More info about models can be found in the Codeigniter docs:
http://codeigniter.com/user_guide/general/models.html

CodeIgniter is flexible, and leaves this decision up to you. The user's guide does not say one way or the other how you should organize your code.
That said, to keep your code clean and easy to maintain I would recommend an approach where you try to limit each model to dealing with an individual table, or at least a single database entity. You certainly want to avoid having a single model to handle all of your database tables.

For my taste, CodeIgniter is too flexible here - I'd rather call it vague. A CI "model" has no spec, no interface, it can be things as different as:
An entity domain object, where each instance represents basically a record of a table. Sometimes it's an "anemic" domain object, each property maps directly to a DB column, little behaviour and little or no understanding of objects relationships and "graphs" (say, foreign keys in the DB are just integer ids in PHP). Or it can also be a "rich (or true) domain object", with all the business intelligence, and also knows about relations: say instead of $person->getAccountId() (returns int) we have $person->getAccount(); perhaps also knows how to persist itself (and perhaps also the full graph or related object - perhaps some notion of "dirtiness").
A service object, related to objects persistence and/or general DB querying: be a DataMapper, a DAO, etc. In this case we have typically one single instance (singleton) of the object (little or no state), typically one per DB table or per domain class.
When you read, in CI docs or forums, about , say, the Person model you can never know what kind of patter we are dealing with. Worse: frequently it's a ungly mix of those fundamentally different patterns.
This informality/vagueness is not specific to CI, rather to PHP frameworks, in my experience.

Related

How to map SQL queries to in-memory model objects?

Let's say we are structuring an application with MVC (also, Stores/Services). SQL is used as the persistence mechanism. And memory efficiency is a major concern.
Obviously, we should take advantage of SQL queries and only ask for fields of our Model in theory object when they are needed.
For example, an mobile app may need to display a list of title for articles, while the body of the article doesn't get displayed until user taps on a specific title. In this case, we ask SQL for just the titles first.
The question is, what should the model object look like?
The solutions I can think of are:
Enhance the model with some states that indicate which fields are populated. This could also be archived by using nil/NULL/None values on unpopulated fields of the model object.
Split the theoretical model to multiple classes. Following the previous example, we could have an Article class and an ArticleDetail class, with a one-to-one relation.
Forget the Store object, let each model object lazy evaluate it's costly fields. The model would have to know about its persistence mechanism.
This should be a common problem. How do the ORM in your favorite frameworks/libraries resolve it? Any best practices?

CodeIgniter MVC Model Logic

I have programmed in Rails, Django, Zend, and CakePHP. Also, Wordpress and Drupal.
Now, I am "catching up to speed" in as fairly large application in CodeIgniter.
Typically, my experience with MVC frameworks, has led me to believe that Models represent business logic in reference to actual database tables. In the CodeIgniter docs and in the code base I'm dissecting I see models created that represent something as vague as a page. A lot of the business logic is written directly into those models and they incorporate other actual data models. I'm not sure this is ideal and following MVC.
Should models be created beyond data models?
Also, lets say I have a data model representing a user (user table in DB). In that user table there is a column called gender of the type enum('male', 'female'). Now I want to populate a dropdown with the gender options from the enum column.
Where is it most appropriate to put this logic?
The user model is an object used to represent a single user or row in the db... right? So it doesn't seem fitting to include a function in the user model/class called "get_gender_options", because, while the function is related to the user table, it is NOT relevant to a single user object. In Zend this kind of logic could be built into the form object itself.
There is not "right" answer, just one we can consider the most appropriate...
I would probably just put the "get_gender_options" in the model, rather than sticking it in the view for the form. To keep it DRY but not put it in the model, I would create a helper to hold this.

LINQ DataContext Object Model, could it be used to manage a changing data structure

I am currently working on a project where we are rewriting software that was originally written in Visual DataFlex and we are changing it to use SQL and rewriting it into a C# client program and a C#/ASP.Net website. The current database for this is really horrible and has just had columns added to table or pipe(|) characters stuck between the cell values when they needed to add new fields. So we have things like a person table with over 200 columns because stuff like 6 lots of (addressline1, addressline2, town, city, country, postcode) columns for storing different addresses (home/postal/accountPostal/ect...).
What we would like to do is restructure the database, but we also need to keep using the current structure so that the original software can still work as well. What I would like to know is would it be possible using Linq to write a DataContext Object Model Class that could sort of interpret the data base structures so that we could continue to use the current database structure, but to the code it could look like we where using the new structure, and then once different modules of the software are rewritten we could change the object model to use the correct data structure???
First of all, since you mention the DataContext I think you're looking at Linq to SQL? I would advice to use the Entity Framework. The Entity Framework has more advanced modeling capabilities that you can use in a scenario as yours. It has the ability to construct for example a type from multiple tables, use inheritance or complex types.
The Entity Framework creates a model for you that consists of three parts.
SSDL which stores how your database looks.
CSDL which stores your model (your objects and the relationships between them)
MSL which tells the Entity Framework how to map from your objects to the database structure.
Using this you can have a legacy database and map this to a Domain Model that's more suited to your needs.
The Entity Framework has the ability to create a starting model from your database (where all tables, columns and associations are mapped) en then you can begin restructuring this model.
These classes are generated as partial so you could extend them by for exampling splitting the database piped fields into separate properties.
Have you also thought about using Views? If possible you could at views to your database that give you a nicer dataschema to work with and then base your model on the views in combination with stored procedures.
Hope this gives you any ideas.

In a MVC web application, who is responsible for filtering large collections of objects, view or model?

I have a web application built on an MVC design.
I have a database which contains a large number of objects (forum threads) which I can't load into memory at once. I now want to display (part of) this collection with different filters in effect (kinda like what stackoverflow does with questions sorted by date, votes, tags etc).
Where do I implement the filtering logic? It seems to me that this must go into the model part of the application, as only models interact with the database (in my implementation). If I make the filtering a part of the view, then the view must access the database directly to get the list of filtered objects, right? I'd like to avoid this, because it exposes the database layout to the view. But at the same time, displaying different views of the same data should be implemented in the view part of the application, as they are just that -- different views of the same data.
So how do I resolve this? Do I create an additional model, say, FilteredThreadsList, and have it remember the filter to use, and then use a FilteredView to display the list of threads that FilteredThreadsList spits out?
Or do I have to build a ThreadQueryier that allows views to query the database for certain thread objects, so I can have the filtering logic in a view without exposing the database backend?
You should never query data from the view. I don't know what framework you are using in particular but as for Ruby on Rails (should be the same for other frameworks) we always pull the necessary data from the controller and store all that information into a variable. The variable will be accessed by the view which can help you avoid querying your database directly from the view.If the code to query the database gets too lengthy in the controller, insert that code into the model instead so it's more maintainable for your project in the future. Additionally, you can call this model method from multiple places in your application if needed. Good luck!
From an architectural point of view, the model should be having the code for filtering. This is so, because in many applications the code for filtering is not trivial and has a good amount of domain logic in it. (Think of filtering top gainers from a list of stocks). From your example as well, it looks the same since you might want to filter by vote or by date or by tags and then by answered or unanswered etc.
In some very simple applications that deal with search/list of entities and allows Create/Read/Update/Delete of an entity, the pagination, sorting and filtering logic is usually very generic and can be implemented in a controller base class that is inherited by all entity-specific controller classes.
The bottom line is this: if your filtering logic is generic put it in the controller else put it in the model.
Model, that's only bunch of entities.
View provides a visual representation of the data from model - use as much of views as you want. If your application is web based, you can fetch data into browser just once (AJAX) using and re-use them for different UI components rendered in the browser.
As for what entities and what view to use for their representation, I think it's work of Controller. If you need some support for it on "model layer", add it but avoid tight coupling.

Multiple Table Models with MVC?

I am just getting started with MVC, and it seems like it will be a great way to go, once I manage to switch my thinking to it.
Most of the material I have come across seems to have a 1-1 relationship between models, views, and tables - ie each model represents a table and allows CRUD, plus more complex functions.
What if I have an Account Model, which would allow account creation and updating.
I would want to use a /signup view and controller to create() the account, but would want to use a /members/account view and controller to update, change pw, etc.
Would it be better to have a Signup Model, or am I ok with just using whatever model I need from multiple locations?
Also, say an account can have many users, but I want to create the first user at signup. I would like to run the account setup and user creation as a transaction. Should I have an Account Model and User Model, and work with both, or just have the signup create() function for Account create the default user?
I am using PHP with CodeIgniter
In general, what you want to do is most likely to consider your tables to be an additional "layer" below your model; the MVC concept generally doesn't deal too much with the implementation of backing issues; i.e. whether or not you're using DB tables or flat file storage or in-memory data representations.
What I would suggest is to look at the problem as one of having one layer that does interaction between your tables and your application; your "data objects" layer. Think of this as pure serialization. If you're using an object model, this will be your ORM layer.
Then you want to have another layer that defines the "business logic"; i.e. the interaction of your data with your data. This has to do with things such as how the Account interacts with the User, etc. The encapsulation here basically takes care of your high-level interactions. In this way, you can define the abstractions that make the most sense for your business requirements without needing to depend on implementation; for example, you can define a "UserAccount" Model, that will do all the things that you need to do to handle User Accounts; define all the things that you want that abstraction to do. Then, once you've got that abstraction down, that is your Model; you can then define, in the internal workings of that model, how the interactions occur with your persistence code.
In this way, you abstract out the persistence and implementation of your Model from the actual Model interface. So you can define your model as doing the things you want it to do without concern for the underlying implementation. The benefits of this are significant; the process of thinking about what you want your Model to do, in isolation from the way in which it will be doing it, can be very instructional; as well, if your backing data layer changes, your Model doesn't need to change; so you can prototype with a flat file, for example.

Resources