Tuesday, February 7, 2012

Maintain a DRY philosophy in Codeigniter


This is my second part in why I really like Codeigniter, it follows on from this post. Whereas the first post was a comparison of Codeigniter and Yii, this post is purely Codeigniter related.

When you first learn Codeigniter, you will build your controllers, models and views and plug them all in accordingly. Ok, now imagine a situation where you have multiple controllers, i.e. News, Content and Testimonial - all are part of the application and all the controllers need the same basic information/variables passed through to the views for output. To make life easier for yourself you could create a very 'fat' controller and keep all functionality inside said controller, but my preference is always to use multiple 'thin' controllers as it makes application much easier to manage.

Imagine you have to build a large application which has many, many different subject areas, with multiple features, i.e. Admin areas, customer areas, public areas and you need to do it in an efficient manner. This is where the DRY (Do not repeat yourself) approach comes in handy, very handy.

For example an array of dynamically generated links that are being created from a class you have written. Using a DRY philosophy you only want to call your link generating method once, not once in every controller or method/action. This is how to do it.

In a lot of Codeigniter examples found on the web you will see the following being used:

$this->load->view('view-page',$data);

...which passes the data from your controller in to your view.

However, you do have another tool that you can use accomplishing this task and that is the method:

$this->load->vars();

So in your your constructor method, you are going to use the $this->load->vars() method to pass through your links array in to each of your methods/actions like so:

class news extends CI_Controller {

function __construct() {
    $data['links'] = $this->link_generator->get_links();
    $this->load->vars($data);
}

function list_news() {
    //code to go here
}

function news_item() {
     //code to go here
}

}



Using the above, every single method/action that is called will be able to successfully access the links variable.

Now, and this is where it gets a little more complicated, we are going to take the above and combine it with extending the CI_controller, so that we can use the code we created in the construct method in all our controllers, so that we do not repeat ourselves. Please believe me, once you have mastered extending the Basic CI controller, the amount of work you will find yourself doing will decrease considerably.

As I do not like to steal other people's work I will point you in this direction: here which will take you to a post from a chap named Phil Sturgeon. Once you have mastered that, you should be able to apply the examples above in to base classes you create using Phil Sturgeon's methods.

I for example, create a base class for every major area of the website and most of my applications have this structure when it comes to base classes.

-- base_admin
-- base_public

...with each controller extending the ones above. Using this method then allows me, for example to add in all my session and user identity checks within my base admin class' constructor and it only has to be called once, rather than in every single controller.  Of course, this is only one simple example, believe me, you can do some really cool stuff with this. I have used this method in so many ways; in shopping sites, user based driven sites, so please give it a go, you'll be extremely glad you did.



Labels: , , , , ,

Friday, December 30, 2011

Use search with Codeigniter pagination

Like I mentioned in a previous post, Codeigniter is extremely flexible and the following code is a perfect example of this. This post on using search with Codeigniter pagination uses only standard Codeigniter functions and requires no extra classes or functions.

Benefits to using this method

No need to use any caching to pass information across pages
No need to use any JavaScript / jQuery to amend links
You can pass any number of parameters through the $_GET array - these may include number of links per page, result ordering information etc. as it rebuilds the URL at page load

Downsides

You are using GET which isn't really the Codeigniter way

Notes on usage

This solution requires a form submitted through GET

The beauty of this method is that it allows the programmer to use any number of form fields. There is no need to use a session cookie to keep track of what a user is searching for, it is all done through the $_GET array.

The example uses some pretty standard stuff in terms of Codeigniter. I have called my model 'm_db_results', but that will probably be something completely different in your application. You could also improve the script by writing a better method for counting your results, I use this method for brevity only.

For all other info or help, just follow the inline help :)

public function search() {
 
    $this->load->model('m_db_results');                
    $this->load->library('pagination');
 
    //you can add any key => value parameter to your base_url
    //it just needs one to create a well formed GET request
    $config['base_url'] = '/site/search/?search=true';        

    // as we are unsure as to what values are going to passed to your pagination page
    // we need to build the base url on the fly  
    foreach ($_GET as $key=>$value) {
       if ($key != 'search' && $key != 'offset') {
           $config['base_url'] .= '&'.$key.'='.$value;
       }
    }
 
    //this will need to go to a model method which determines the total number of results
    //based on your form/search parameters. In my case the model method takes an array which in this case
    //is based on key/value pairs that are same mapped the same as the form inputs
    $results_info = $this->m_db_results->search($_GET);
 
    //the key to using this is that it will append your uri with the query string segment parameter
    //using this allows in conjunction with the $config['page_query_string'] being set to true
    //as it adds the offset to the URI as &offset=x
    $config['query_string_segment'] = 'offset';
    $config['page_query_string'] = true;

    $config['total_rows'] = count($results_info);
    $config['per_page'] = $number_per_page = 10;
 
    //now instead of using the uri segment to determine the number of results we offset
    //from our results we use the parameter we specified above in the $config['query_string_segment']      
    if (!empty($_GET['offset'])) {
       $offset = $_GET['offset'];
    } else {
       $offset = 0;
    }

   $this->pagination->initialize($config);
 
    //now we run the same method as above but we supply an amount of results we want to be returned and the offset
    //as the second and third parameters
    //and pass off the data to our view
    $data['results'] = $this->m_db_results->search($_GET, $number_per_page, $offset);
    $this->load->view('results-page.php', $data);

}

Further info

Now as your form is submitted through get, it will not be able to use the set_value() method if you normally use that to repopulate your forms. You will have to code it in yourself, more than likely using isset() or empty() to determine if the field has a value.

P.S. If you found this post useful or not, can you leave some feedback in the comments as I want to improve the code as much as I can for other 'igniter fans. Thanks

Labels: , , ,

Wednesday, June 1, 2011

Codeigniter Versus Yii - my thoughts

Codeigniter versus Yii, now this may open a real can of worms, as most comparisons do, but I have used both and have to come to the conclusion that whilst Yii is probably that slightly more polished, Codeigniter is going to be my framework of choice for next few years to come when developing websites in PHP.

Let's take a look at Codeigniter, it's easy to learn, easy to grasp and now that it has been upgraded to version PHP5 only from version 2 onwards, much more future proof. I also really like the way that you can really, really customise it to do your bidding. No need to use the command line to get it up and running and it will run with a very small footprint. You can also cache the hell the out of it at multiple levels to squeeze every little bit of performance out of it, take a look here for a detailed look at this.

Now let's look at Yii, completely object oriented and its major, major advantage - The CRUD generator. My goodness, this saves you time, lots of time. You create your database, design your schema and bang the Gii tool produces (as if by magic :)) your create, read, update and delete pages. No mucking around no writing SQL, it's all done through the (Rails inspired) Active Record Pattern - it's fair to say I fell in love with this almost straight away, I couldn't believe how easy it was to create this code. And this is what got me thinking...

I like Codeigniter for its flexibility, the way you could use both an active record pattern or traditional SQL, You could keep your database results in arrays or as standards objects, they leave it up to you. But I wanted, no, no... I needed a CRUD generator after experiencing the wonders of the Gii tool. As a freelance web developer in Lancashire (I know this sounds cheesy) time is money, so I scoured the web for one and I found a couple out there and none really lived up to my expectations, one was particularly good, but didn't really suit my needs. Like I said, I liked Codeigniter because of its flexibility, so I decided to bite the built and create my own CRUD generator for Codeigniter. Yeah, sure it was going to take a little bit of development time, but the time saved will definitely outweigh the initial outlay and it does, plus as my CRUD tool was my own, I could tweak and make changes very easily. Now, when creating large projects, creating new sections is not the chore it once was and now leaves me more time to make the other, more unique features, just right.

The main point that many people raise when they compare the two frameworks is the way that Codeigniter is not truly object oriented, whilst Yii is much more pure in its implementation. I suppose this is true, but when I create applications that are large, I need to know that I can hack away at them very easily and tune them to my specific needs and it is for this reason above all else that Codeigniter remains my PHP framework of choice.

When I first set out developing websites using PHP, I though this was the language I would use forever when it came developing websites. I als felt like I would never, ever use a framework as how could using some else's ideas and code be of any benefit to me, when I have wrote my own application. Not only is the code battle ready as it has been through countless improvements through being used in the community, it also oipens up your mind to new ways of thinking. I learnt to use Codeigniter first and Yii second, but there are things used in Yii, that I will and have ported over in to Codeigniter, the way Yii authenticates users for example, is a great way of accomplishing this task.

It's like I have mentioned before in other posts, do not do what other people tell you should do. Sure take on board what other people have, but stick to what you are comfortable with using as it is you that is creating the application and not them.

Labels: , , , ,

Sunday, March 6, 2011

Phew, how busy...

Very, very busy at the moment. Along with the welcomed addition of my little daughter O have websites coming out of my ears.

Anyhow. I have launched a couple of mini sites this weekend. One named Man of Steel for myself as I like to archive information about the new Superman movie. I am sure there are hundreds of other sites out there, but it is mainly for me so I can go back and look at how the movie shaped up over time. As you may guess I am a huge Superman fan and I can't wait see what Zack Snyder does with the franchise.

The other is a hobby site for a friend of mine, named the Pensioner's Voice. This was a a favour, has very little design, but the information is incredibly useful.

Oh in terms, of technical information, they were both built using the PHP Codeigniter Franmework version 1.7 using a MySQL 5 database.

All the best,
James

Labels: , ,

Monday, January 10, 2011

Organise controllers in Codeigniter using subfolders

This is my extended guide to using folders in Codeigniter. There are a couple of guides out there, but I thought a more detailed with step by step guides.

In this instance I will be creating a very common controller named 'Admin' with a basic controller named 'login' within a folder named 'secure' - its URI will look like this:

http://www.domain.com/secure/admin/login

First, go to your 'Controllers' Folder
Then add a folder named 'secure' - this will contain your new set of controllers.
We then create a file within the new folder named 'admin.php' - the new controller file

Declare your subclass:

<?php
class admin extends Controller {

function __construct() {
parent::Controller();
}

function login() {
//your code to go here
}

}
?>

Adding a default

When you add a controller folder, you can also add in the default controller to run should the person viewing the site not enter a controller name, for example:

http://www.domain.com/secure/

You add the default like so:

Create a new file and name it the same as your default controller name in 'routes.php', the default controller in Codeigniter is 'welcome', so that is what we will create:

controllers/secure/welcome.php

We then need to create the code for this file:

class welcome extends Controller {

function __construct() {
parent::Controller();
}

function index() {
//your code to go here
}

}

For more information on Codeigniter and how Controllers work within go to:http://codeigniter.com/user_guide/general/controllers.html

Labels: , , ,

Wednesday, November 24, 2010

Book Review of Professional Codeigniter - Wrox Publishing

Author: Thomas Myer
First Published: 2008
Pages: 314
Purchased From: amazon.co.uk
ISBN: 978-0470282458
Skill Level: Intermediate to Advanced
Categories: PHP, PHP Frameworks, Programming, Technical

Reason for purchasing book:
I had been playing around with my own MVC design pattern in PHP for a while and decided that it was time to learn a framework. After looking at the various ones out there, I decided that codeigniter would be the [first] one for me. I chose 'Professional Codeigniter' as the title suggests (and having bought other Wrox Books) that it is aimed at people who have moved past being a 'Beginner'.

Initial Thoughts
The book starts off with a little introduction about the author and many of the other things that you would normally find at the beginning of a book.

He also explains in detail why he started using the framework in the first place. This was very much welcomed as you can see that Thomas Myer was indeed a programmer who had a real need for using the framework, rather than just being another author who saw an opportunity to make some money from creating a book.

Structure
One of the stand out features of this book is the way the order of each section is delivered to you. First we have an introduction to the world of MVC and why it is such a great design pattern. For those who have never used the MVC, this section is a great introduction, is written well and will bring many a coder up to speed in a short amount of time. This is mainly achieved by looking at older coding styles and how they lack structure of a real design pattern. He also looks at other PHP frameworks so that you understand how each one works and why Codeigniter is such a good choice. We then get on to the main part of the site and how to build a website (specifically an ecommerce website) using Codeigniter and it does this very well, taking you from the early stages right of concept creation and customer meetings right through to the delivery.

Technical Considerations
Part of modern web design and development now focuses on an Agile Methodology, whereby software is created in small manageable sections using teams. This section is also explained very well, so if this concept is something that is new to you or you need certain points clarifying.

Something else I should point out is that this book really could be split in to three separate sections. From chapters 1-4 you are giving a great deal information on how to use Codeigniter to create a website and how to get it working. Chapters 5-8 are more along the lines of adding the ecommerce sections and finally chapters 9 and 10 on how to secure and launch the site. For me the stand out chapter was chapter 3 and in its own right would serve as a great reference.

I do have slight problem with this book and that is the lack of content on Codeigniter's form validation. When you create a website, especially an e-commerce website, you create many, many forms. These forms, especially when dealing with commerce is extremely important and the data that you collect has to be absolutely spot on. I understand that the scenarios in the book may have not required the use of the Form Validation class to be used to the level, but I do feel these methods should have been addressed.

He does use the form validator but not to the extent that uses the rules and data filters. Instead I found myself turning to the web and using online guides to help me with this. One thing I add though, is that like many open source frameworks, Codeigniter moves at a very swift pace and the libraries that are available now may be very different to the ones that were used when the book was written, so for that reason I will give the author the benefit of the doubt.

Final Thoughts

Overall, a fantastic book. You will not be disappointed with this title and you will definitely be able to use Codeigniter fluently by the time you have finished with it. Like I mentioned the only problem is the lack of depth in the form validation class, but these pages will fill in any gaps:

http://codeigniter.com/user_guide/libraries/form_validation.html
http://www.packtpub.com/article/form-validation-with-codeigniter-1.7

Score: 4.5 out of 5 - Highly Recommeded

Labels: , , , ,