How to use a “Cookbook” with Codeigniter

cookbookI was asked to do a review for Codeigniter 2 Cookbook, written by Rob Foster and published by Packt Publishing (to be honest, I actually asked to review the book to get it for free).

I haven’t managed to keep the promise of reviewing the book in due time, but suddenly I realised that every now and then I return to the book to uncover a new programming style that makes me say: “Ahaaa”. Continue reading

rules

Forms? Keep the validation rules inside the model

As always, when talking about forms we also talk about validation. For a long time I’ve validated the forms inside the controllers because it is fast and simple – no more browsing between files.

But after a while you find yourself having a controller which is becoming more complex and bigger. So why not keep at least the validation rules somewhere else?

One solution would be to keep all the validation rules inside a config file, and organize the rules into “groups”. I will talk about this method in another post.

The other solution would be to put the validation rules inside the model, which, in my opinion would make more sense, considering that every form element is actually a column inside your database tables.

As you can see, you can make an array that contains different rules depending on the forms that are used. The array is public, so that it can be accessed directly by the controller. Regarding password, there will be alot of people arguing that I can’t just verify plain password against the database and that the password needs to be encrypted. Yet this is not the scope of this post. I only wanted to give an example about how to keep the rules inside the model.

Now, going to the controller, you simply call the rules:

I won’t go and make the view, that not being the point of this post. The only thing I hope you understand is that every form element must be named exactly like the keys inside the array we defined in the model (first_name, last_name, email, password, etc.).

models

Codeigniter: My MY_Model or “How not to repeat yourself”

Often times I find myself doing the same queries over and over again for each table used by an application. This is why I needed to create an “universal” model in order to avoid repetition. Codeigniter lets you do that by allowing you to create a “MY_Model” inside the core folder of your application. Continue reading

database

CodeIgniter: How to retrieve data from a database

What is a dynamic site without databases, right? Yesterday someone asked me to make a tutorial about retrieving data from a database using CodeIgniter. As a self-respecting framework, CodeIgniter is adhering to the Model-View-Controller philosophy, i.e. is using the Models to interact with the database. For starters I will assume that you already have installed CodeIgniter, and you have a MySQL database installed on your webserver. Continue reading