Friday, December 24, 2010

The Flexibility of PHP

I have been using PHP for 4 years now and I like to think I know it pretty well by now. It's a great language, it is open source, has regular updates and fixes, and has a great online manual.

What you also get when you talk to other developers who use other technologies is that it is non-complied and uses the 'Spaghetti' coding style where you have SQL in with your code, along with the formatting of the results returned from the database and all your HTML.

Well, for them and other people who are looking to learn a Server side Web Programming language, PHP is not sub standard, PHP is flexible - let me explain. People are also under the opinion that PHP is an easier language to learn than many other languages and yes it can be, but only because it is flexible and allows you to explore it from a number of different angles.

First, let's take a look at the 'Spaghetti' option, yes it is a little in efficient and yes it CAN be hard to edit if you have to come back to it in the future. But if you are new to programming and web development then it is the perfect way to start. You can learn the other (multi-tier) methods when you feel a little more comfortable. When you first learn to program, learning using a procedural manner is a great way to learn a language, the way it behaves and how logic determines specific conditions. Once you have these skills mastered, you can then start to apply them to more advanced methods, i.e. Object Oriented Programming.

For those who have never seen a bit of PHP 'Spaghetti' Code it looks a little like this:

<?php
    $SQL = "SELECT field1 FROM table";
    $query= mysqli_query($databaseLink,$SQL);
    while($row = mysqli_fetch_array($query,MYSQL_ASSOC)) {
       echo '<div class="tableResult">'.$row['field1'].'</div>';
   }
?>

The other option is to use a multi-tiered approach which could use Object Oriented Methods. When you use this approach, it works around the basis of separating code into different sections. When I first learnt OOP I used a two tier approach as I was a freelance developer and as such I thought that it was the best way to go. My two tier approach could very be different from another developer's 2 tier approach, but again, this is the flexibility of PHP. My 2 approach worked on the basis of keeping my Application Logic and my presentation in 1 tier and my business and data logic in another tier. When I created an application, I would follow this method and it served me well, across numerous (and large) applications. If I wanted to use a class, I would invoke it in the logic based file, the results would be sent back and the logic based file would process, format and output the results. The next example uses a separate database class but premise is the same, that the database and application classes from the controller or or input decision file.

//database class
class database {
public function retrieveResults ($SQL) {
$rows = array();
$query= mysqli_query($database,$SQL);
while($row = mysqli_fetch_array($query,MYSQL_ASSOC)) {
$rows[] = $row;
}
return $rows;
}
}

//application class
class application {
public function getTableData() {
$SQL = "SELECT field1 FROM table";
$useDatabaseClass = new database();
$results = $useDatabaseClass->retrieveResults($SQL);
return ($results);
}
}

//calling script
$useApplication = new application();
$getData = $useApplication->getTableData();

foreach ($getData as $row) {
echo '<div class="tableResult">'.$row['field1'].'</div>';
}

Then there is the 3 tier approach - one popular name for it is the MVC approach. This is where you separate application logic, data handling and presentation in to their three separate components. This is useful to use when you on any project, but I found it of most useful since I have been working in a design agency, as I work on multiple projects on any one time and front end guys who work there need to access many of the view files. Please note that the way you call scripts in reality would probably not look like the above, these are just for illustration purposes. In reality, if you use an MVC framework or you create your own, you would more likely extend your base classes rather invoking them using the new keyword.

The three tier is very similar to the two tier approach. Except that the $getData array is passed through to another file which outputs the results using the foreach loop. That's it, the hard work is really done when you move from one tier to two tiers, the third tier (the view tier) is really just a minor extension of the controller tier, which in my opinion works in tandem with the Model or Business Tier. The view or presentation file can be loaded in a number of ways, using include() or require() or even eval().

A few last words, when you start down your PHP developer career, do not let anyone tell you which method to use, weigh up the situation and make an informed decision. I like to build my online applications using 3 tiers using codeigniter as the MVC framework, but I still write single standalone scripts when I feel the situation needs it

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