Archive for October, 2008

Object Oriented Programming (OOP) and PHP

When I first started university I knew a bit of PHP and managed to mackle together lines of procedural code to preform basic functionality on a website such as add, edit, delete and view data within a MySQL database. Within my 2nd year I was introduced to a book (PHP Objects, Patterns and Practise) that changed my life.

I studied it chapter to chapter until I got bored and decided to actually try to do something with my new found knowledge and started writing very basic Object Oriented PHP using the poorly implemented PHP4 OOP syntax. I slowly grasped the concepts and pieced together a basic framework to increase my development time and stop me from constantly rewriting the same code over and over again.

Most of my developments came from writing my first online application which is a productitiy tool we use to manage all our clients, jobs, quotes, and passwords. The main benefit at this level was the use of a database and paging class which proves to be a ball ake for anyone that still writes procedural PHP.

After grasping the concepts I quickly moved over to PHP5s OOP syntax which has a far greater support for the Object Oriented approach. The move from OOP in PHP4 to PHP5 is about  the same level as moving from procedural programming to Object Oriented Programming with hordes of new functionality that should be expected of any OOP language.

Personally I actually find Object Oriented Programming easer than Procedural its the move between the two that causes problems with the method of working being a completely different approach.

OOP revolves around data rather than actions much the opposite to Procedural. A common example is the following:

<?php
class books{
	//private means can only be accessed from within the class
	private $title;
	private $author;
	private $isbn;
	private $year;

	//the __construct function is called as soon as the object is created.
	//Public means the method can be accessed from anywhere inside or outside the class
	public function __construct($title, $author, $isbn, $year){
		//$this refers to this class (books). In this case it is referring to private $title; found in line 4
		$this->title = $title;
		$this->author = $author
		$this->isbn = $isbn;
		$this->year = $year;
	}

	//notice how you do not need to pass $this->title into the method
	public function checktitle(){
		//check the book title only contains 0-9 a-z (uppercase or lowercase) hyphens, underscores and spaces
		if (eregi("([a-z0-9-_ ]+)", $this->title))
			{
				return true;
			}
		return 0;
	}

	public function checkauthor(){
		//check the book author only contains 0-9 a-z (uppercase or lowercase) hyphens, underscores and spaces
		if (eregi("([a-z0-9-_]+)", $this->author))
			{
				return true;
			}
		return 0;
	}

	public function checkisbn(){
		//check the book author only contains 0-9 and is 13 characters long
		if (eregi("([0-9]{13})", $this->isbn))
			{
				return true;
			}
		return 0;
	}

	public function checkyear(){
		//check the book author only contains 0-9 and is 4 characters long
		if (eregi("([0-9]{4})", $this->year))
			{
				return true;
			}
		return 0;
	}
	//run all the validation checks return true if all pass
	public function validate(){
		if (!$this->checktitle()){
			return false;
		}
		if (!$this->checkauthor()){
			return false;
		}
		if (!$this->checkisbn()){
			return false;
		}
		if (!$this->checkyear()){
			return false;
		}
		return true;
	}

	public function save(){
		//save the file into the database
	}
	//this is the last thing to run on the script
	public function __destruct(){
		unset($this->title, $this->author, $this->isbn, $this->year);
	}
}
//create an object $books
$books = new books('PHP Objects, Patterns, &amp; Practice', 'Matt Zandstra', '9781590599099', '2008');

//this will return a fatal error becase we are trying to echo a private object variable
echo $books->title;
//notice how we are using $books->title rather than $this->title because we are outside the class

//check if the title is valid
if ($books->checktitle()){
		echo 'This book title is valid'; //does not echo because the title contains , and &amp;
	}
//check if the author is valid
if ($books->checkauthor()){
		echo 'This book author is valid'; //this will echo because the string contains no illegal characters
	}
//save the data into the database if all the validation is passed
if ($books->validate()){
	$books->save();
}
//now the script has finished running __destruct will be called and unset all the object variables
?>

This is a very basic class and the books idea is a very common analogy when teaching Object Oriented Programming. Whenever you want to add a new book and check that the data is valid you can simply create a new object with the following code:

<?php
$books = new books('my title', 'my author', 'isbn', 'my year');
//if passes validation save into database
if ($books->validate()){
$books->save();
}
?>

If you were to want to preform the same function with Procedural PHP you would need to rewrite all the same code again. This takes time effort and in a commercial environment money.

Hopefully what I have written will help you grasp the concepts of Object Oriented Programming with PHP5 and pull you away from your Procedural habits.

I hope to expand on this and slowly start to show the true potential of OOP in Online Application Development.

Useful Links and Resources:

  • Share/Bookmark

An approach to cross browser compatibility

Some browsers make our lives a misery with their varying standards, different box models and lack of support for the shiny new tools we keep being offered. This is not a guide or tutorial but an insight into some of the problems you may face with cross browser compatibility and how to approach them.

It’s sad to say that around 20% of the users on the internet are still sitting at home or work with Internet Explorer 6. I pick on this browser because is it the bane of my life with my experiences today being on exception. I spent over half the day trying to get a complex drop shadow design using PNG’s to work.

I am ashamed to admit it beat me and I resolved the problem by creating an Internet Explorer 6 style sheet using jpegs for the background images. This also required to solve the problem with the box model Internet Explorer 6 implements.

It isn’t just Internet Explorer that causes problems when creating a new website all browsers have their own little quirks and ways of doing things. Another factor to consider is the operating system the user is working on Windows always seems to render fonts slightly bigger than Mac etc…

When you need cross browser compatibility you need it within the foundations of your site. It is not cost or time effective to try to make your site compatible after you have put all the hard work in making it look perfect in your browser of choice.

Start with markup:

Content if the foundation of your site despite some of you designers out there wanting your beautiful design to be the feature of the site. It is not what the user keeps coming back for. HTML (Hypertext Markup Language) is exactly what it states in its name MARKUP.

This is where I rant about semantics and how important they are. HTML has a fairly strict syntax of tags to mark up the content of our websites. H1-H6 provide us with a layered approach to headings allowing us to specify a hierarchy of content within our site. P provides us with the ability to specify paragraphs rather than having a mountain of <br/> tags giving little structure to any content. The list goes on and this is how you should structure your content before you even think about how your design is going to work into the markup.

So to recap over my waffling: Write your markup around your content (or test content) before you even think about CSS or design. Also use xHTML strict. Transitional is a cop-out!

Most importantly use a doctype

Prepare with CSS:

A CSS layout doesn’t mean loads of DIV tags to put your content into your design. CSS is about separating content, design and functionality. Separating these provides a layered approach for any user allowing their setup to give them as much or little functionality as they want without impacting on the value of the content.

Every style sheet I write starts with

*{
border:0;
margin:0;
padding:0;
}

This clears all the horrible, varying default margins, padding and borders added by each browser. By doing this you decrease the chance of areas of your site being about by the default values that each browser implements.

Where possible when naming your styles use names based on its content over its location on the page this allows future flexibility with minimal work especially if you wanted to move a section of content from one column to another. This isn’t a cross browser tip but is comes in handy later down the line.

Understand your browsers and accommodating to their differences:

So you have your semantic xHTML and have styled up your content with your CSS but things just don’t seem to be displaying right when you jump from browser to browser. This is pretty much inevitable when building a new site and you have to start using different techniques to get some of the browsers to display your content is a format which is both visually appealing and usable.

The most common method is by using hacks. We all hate using them and it makes us feel dirty but over the years I have come to accept that I have to use them to accommodate for as many users as possible. My preferred method is to use a conditional comment and separate style sheet to adjust my current styles.

<!--[if IE 6]>
<link rel='stylesheet' href='/styles/mysite-ie6.css' type='text/css' media='all' />
<![endif]-->

This provides a clean and effective way of working with Internet Explorer 6 without having to use unconventional methods that could interfere with future browser releases. The same methodology can be applied to other browsers as well but the need for them is generally lower than Internet Explorer 6. Most current up to date browsers work on the same basic principals and box models with slight variations and adjustments to your CSS can get a consistent layout/design across different browsers and platforms.

Conclusion:

Rather than ramble on any more I have decided to put together a list of simple points to remember:

  • Design and Style around your content not the other way around
  • ALWAYS use a doctype otherwise browsers will be thrown into quirks mode
  • Semantically markup your content first. Don’t even think about design/styling.
  • Apply your styles to your content adding any extra markup such as div containers if required.
  • Use a standard browser such as Firefox and download the developer toolbar + firebug
  • I shouldn’t have to say this but: NEVER USE TABLES FOR LAYOUT
  • Always design/develop for the user not for yourself
  • Everyone has a different setup. More people than you realise are still on 1024×768 resolution and Internet Explorer 6.

Resources and useful links:

  • Share/Bookmark