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: , , , , ,

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: , , ,

Friday, December 10, 2010

Building websites using MVC in PHP

When you start PHP programming you can write some code very quickly and get some very good results very quickly. Quick as a flash you can learn the syntax in a few weeks (especially if you know another language) and in week 3, you can have a dynamic website spitting out information in a variety of ways. That's fine and it CAN serve you well, but it has its problems: scalability, readability and edit-ability (and many other 'abilities) all become increasingly hard to maintain.

When you learn a language, you don't become proficient in it over night, you have to use the language for months and even years before you come to real grips with it. Each language has its own set of intricacies, pitfalls and glitches that set it aside from its peers.

Even when you crack a language, there are number of different ways you can set your site's architecture. For example I went through these stages (and many in between)

Writing pure procedural code was the method I originally. With the odd exception of including the footer, header and my functions file, I was writing code per dynamic page, top down in a procedural manner and I thought great, we have a site and it works pretty well.

I then started to learn more advanced functions, using mod-rewrite to route requests and various other little tools that all made my life a little bit easier. With each passing stage, you look at your code and you honestly think that each iteration is the best you could ever do. That is until you move in to the next stage of your development where you try something new or read about some new fad sweeping the world of programming.

The next stage was learning, using and creating classes to use in Object Oriented Programming (OOP). When I started using OOP I was astounded how much time I was saving when moving from project to project. I had created a database abstraction layer, form builder class, email class, social media class and many, many more that could be used in all my different projects. Again this method was great, I was a lone developer in the agency I worked for and any changes that needed to be made to the code could be done by myself, no problem. As I became a better developer over time I started to hone my scripts and use different folders to separate sections of the websites architecture and things became a little easier to manage. The problem I think came down to me working on my own when it came to the development side. I was using classes and objects but I was still passing SQL from within the page to the database and letting the same page then take those results and outputting the findings. It was at this point I turned to Ruby on Rails and learnt how to make a basic website using Ruby and things became a whole lot clearer. It showed me a structure of how a web site should be built and really opened my eyes to the MVC design pattern. I also realised that what could be done with Rails could surely be done with PHP.

Once I decided that I was I going to use an MVC framework I needed to decide which one to use and after a little bit of reading I made the decision to use Codeigniter and bought a book on the subject. I built a couple of quick sites and decided that I absolutely loved it and that site and application builds were quicker and much easier to maintain. However I also found myself to have a nagging issue. How did this wonderful thing work, so I took it upon myself to write my own little framework. It was a little bit daunting, but I had my own set of classes which I could integrate which and separating the page requests as per the MVC model. You could say that why create your own MVC framework when there are so many available ones out there? Well, it gives you a great understanding of the MVC model and as you are making something that is comparable to the big wigs in the PHP world like Zend and CakePHP (though may be not as substantial) then you can consider the creation as a sort of rite of passage as a developer.

I am not going to go in to massive detail when it comes to building how you you build your own MVC framework but it runs along these lines:

1. Create a rewrite condition in your .htaccess file that routes all requests bar images, css, js to a PHP file (which is generally known as a bootstrap file)
2. Use a bootstrap file to separate your page request in to 2 basic sections. In my case I took the $_SERVER['REQUEST_URI'] value, used explode() on the '/' character and then accessed using $array[0] and $array[1] to access necessary parts of the URL. When this is done you will take an example like this:

http://www.domain.com/products/widgets

Which when broken down would be pointing to a controller named 'products' and and an action named 'widgets'. Once you have these two sections you can start using autoload to start using files automagically which will include your controllers and actions and calls to your views where data can be passed through to be outputted using HTML.

On to the benefits of using an MVC Framework in PHP

You will find numerous pages on the web regarding the benefits to the MVC. I will add the obvious ones and then a few more of my own. With MVC it helps you build sites in team by allowing multiple people or groups access to specific sections of code. You keep all your presentation, application, data handling code separate. Here are a couple more that, while are probably a little less grandiose will still help when it comes to creating your projects and are some of the major benefits that I have found.

I use a PHP IDE named PHPEd and it works really well with both HTML, PHP and CSS. When using the MVC method I refound that I needed to come in and out my PHP and HTML. It makes it much easier to read and with a flick of a button in PHPEd (F12) you can quickly get an overview of all your PHP and HTML separated out. Front end developers can go in, add their elements and nothing is affected (this comes back to the coding in sections) and everyone is happy.

Code becomes more modular, not only does it make it easier to use in other projects. For example, lets take an FAQ section. Lots of sites will use something like this, why completely rewrite for each site. Copy, Paste, Tweek and your done.

When you need to find some code, you always no where it is. The URL tells you where the code is. I work in Digital Agency and I am constantly working on numerous sites and finding code use to be a real pain. All I can say is: it's much easier now!

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: , , , ,

Saturday, October 16, 2010

Magento snippets I find useful

I have created this page as I often find myself working on Magento projects in many different locations and needed a quick reference. You will often find, you will need to add these in to your scripts to get that level of functionality that you need for your magento customisation.

N.B. This page is ongoing and will be updated often. All snippets work on 1.4.11

Singles

//get current controller name
$this->getRequest()->getControllerName(); //returns string

//get Action Name
$this->getRequest()->getActionName(); //returns string

//get Module Name
$this->getRequest()->getModuleName(); //returns string

//get Number of items in user cart
$this->helper('checkout/cart')->getSummaryCount(); //returns number of products

//check if user is logged in
if ($this->helper('customer')->isLoggedIn()) //returns true/false

Combinations

//check if user is on home page
if ($this->getIsHomePage()) { } //returns true/false
//check for home page only works when in header.phtml
//use method below if outside of this file or
//create new instance of:
//Mage_Page_Block_Html_Header() like so:
//$newHeaderObject = new Mage_Page_Block_Html_Header();//
if($newHeaderObject ->getIsHomePage()){} // returns true/false

//alternative method
if (($this->getRequest()->getModuleName() == 'cms') && ($this->getRequest()->getActionName() == 'index')) { } //returns true/false
//use this to check if home page in other template (.phtml) files
//works by checking the module name and the action request.

Labels: , , , ,