Banner

Open Source Blog | Professionals Blog | Blog Sites | Technology Blog

A short description about your blog

I recently worked on the project related to improve the website speed. When I analyzed the files I found that it used a lot of php code which can easily replaced by mysql. There were a scenario where we sort the record in particular order e.g. 2,0,1 and it was accomplished with the help of PHP code.

When I checked the mysql manual I found it can be done easily using ORDER BY FIELD

For e.g. If you have 3 priorities Low, Normal, High and you want to display High records first and then Normal and then Low. We used below query for that and it worked very well and it improved the website loading time.

Select * from table_name ORDER BY FIELD(priority_record, ‘High’,’Normal’,’Low’);


As a programmer, you may aware about the variables and functions in PHP. Classes and objects, though, might be a different matter. It's very much possible to create a perfectly good systems without even defining a single class(es). Even if you decide to stay away from object-oriented programming in your own code, you will likely need to know object-oriented programming. For eg., if you use a third-party library, such as those made available by PHP Extension and Application Repository (PEAR), you will find yourself instantiating objects and calling methods.

What are classes and objects?

Put simply, a class is a discrete block or bundle of variables and methods. These components usually coalesce around a single responsibility or set of responsibilities. In this article, you will create a class that collects methods for querying and populating a dictionary of terms and values.

A class can be used directly as a neat way of organizing data and functionality, very much like a bunch of functions and variables. This is to ignore a powerful dimension, however. Classes can be used to generate multiple instances in memory. Such instances are called objects. Each object has access to the same set of functions (called methods in an object-oriented context), and variables (called properties or instance variables), but the actual value of each variable may differ from object to object.

Think about a unit in a role-playing game -- a tank, perhaps. A class may lay down a set of variables for tanks: defensive and offensive capability, range, health, and so on. The class may also define a set of functions, including move() and attack(). While the system contains one tank class, this class may be used to generate tens or hundreds of tank objects, each potentially with its own characteristics of health or range. A class, then, is a blueprint or template for use in generating objects.

Perhaps the easiest way to understand classes and objects is to create some.



A first class

You can create a class with the class keyword. At its simplest, a class consists of the keyword class, a name, and a code block:

class Dictionary {

}

The class name can contain any combination of letters and numbers, as well as the underscore character, but cannot begin with a number.

The Dictionary class in the previous example is perfectly legal, even if it is of limited use. So how do you use this class to create some objects?

$obj1 = new Dictionary();
$obj2 = new Dictionary();
$obj3 = new Dictionary();

In form at least, instantiating an object is similar to calling a function. As with a function call, you must supply parentheses. Like functions, some classes require that you pass them arguments. You must also use the new keyword. This tells the PHP engine that you wish to instantiate a new object. The returned object can then be stored in a variable for later use.



Properties

Within the body of a class, you can declare special variables called properties. In PHP V4, properties had to be declared with the keyword var. This is still legal syntax, but mainly for the sake of backward compatibility. In PHP V5, properties should be declared public, private, or protected. You can read about these qualifiers in Keywords: Can we have a little privacy in here? But for now, declare all properties public in the examples. Listing 1 shows a class that declares two properties.


Listing 1. A class that declares two properties
                
class Dictionary {
public $translations = array();
public $type ="En";
}

As you can see, you can declare a property and assign its value at the same time. You can get a quick peek at the state of an object with the print_r() function. Listing 2 shows that a Dictionary object now has more to it.


Listing 2. A look at the Dictionary object
                
$en = new Dictionary();
print_r( $en );

If we run this script, we'll see output of:

Dictionary Object
(
[translations] => Array
(
)

[type] => En
)

You can access public object properties using the object operator '->'. So $en->type means the $type property of the Dictionary object referenced by $en. If you can access a property, it means that you can set and get its value. The code in Listing 3 creates two instances of the Dictionary class -- in other words, it instantiates two Dictionary objects. It changes the $type property of one object and adds translations to both:


Listing 3. Creating two instances of the Dictionary class
                
$en = new Dictionary();
$en->translations['TREE'] = "tree";

$fr = new Dictionary();
$fr->type = "Fr";
$fr->translations['TREE'] = "arbre";

foreach ( array( $en, $fr ) as $dict ) {
print "type: {$dict->type} ";
print "TREE: {$dict->translations['TREE']}\n";
}

The script outputs the following:

type: En TREE: tree
type: Fr TREE: arbre

So the Dictionary class is now a little more useful. Individual objects can store distinct sets of keys and values, as well as a flag that tells a client more about the kind of Dictionary this is.

Even though the Dictionary class is currently little more than a wrapper around an associative array, there is some clue to the power of objects here. At this stage, we could represent our sample data pretty well, as shown in Listing 4.


Listing 4. Sample data
                
$en = array(
'translations'=>array( 'TREE' => 'tree' ),
'type'=>'En'
);

$fr = array(
'translations'=>array( 'TREE' => 'arbre' ),
'type'=>'Fr'
);

Although this data structure fulfills the same purpose as the Dictionary class, it provides no guarantee of the structure. If you are passed a Dictionary object, you know it is designed to have a $translations property. Given an associative array, you have no such guarantee. This fact makes a query like $fr['translations']['TREE']; somewhat hit and miss, unless the code making the query is sure of the provenance of the array. This is a key point about objects: The type of an object is a guarantee of its characteristics.

Although there are benefits to storing data with objects, you are missing an entire dimension. Objects can be things, but crucially they can also do things.



Methods

Put simply, methods are functions declared within a class. They are usually -- but not always -- called via an object instance using the object operator. Listing 5 adds a method to the Dictionary class and invokes it.


Listing 5. Adding a method to the Dictionary class
                
class Dictionary {
public $translations = array();
public $type ="En";

function summarize() {
$ret = "Dictionary type: {$this->type}\n";
$ret .= "Terms: ".count( $this->translations )."\n";
return $ret;
}
}

$en = new Dictionary();
$en->translations['TREE'] = "tree";
print $en->summarize();

It provides output of:

Dictionary type: En
Terms: 1

As you can see, the summarize() method is declared just as any function would be declared, except that is done within a class. The summarize() method is invoked via a Dictionary instance using the object operator. The summarize() function accesses properties to provide a short overview of the state of the object.

Notice the use of a feature new to this article. The $this pseudo-variable provides a mechanism for objects to refer to their own properties and methods. Outside of an object, there is a handle you can use to access its elements ($en, in this case). Inside an object, there is no such handle, so you must fall back on $this. If you find $this confusing, try replacing it in your mind with the current instance when you encounter it in code.

Classes are often represented in diagrams using the Universal Modeling Language (UML). The details of the UML are beyond the scope of this article, but such diagrams are nonetheless an excellent way of visualizing class relationships. Figure 1 shows the Dictionary class as it stands. The class name lives in the top layer, properties in the middle, and methods at the bottom.


Figure 1. The Dictionary class shown using the UML
Dictionary class using the UML


The constructor

The PHP engine recognizes a number of "magic" methods. If they are defined, it invokes these methods automatically when the correct circumstances arise. The most commonly implemented of these methods is the constructor method. The PHP engine calls a constructor when the object is instantiated. It is the place to put any essential setup code for your object. In PHP V4, you create a constructor by declaring a method with the same name as that of the class. In V5, you should declare a method called __construct(). Listing 6 shows a constructor that requires a DictionaryIO object.


Listing 6. A construtor that requires a DictionaryIO object
                
class Dictionary {
public $translations = array();
public $type;
public $dictio;

function __construct( $type, DictionaryIO $dictio ) {
$this->type = $type;
$this->dictio=$dictio;
}

//...

To instantiate a Dictionary object, you need to pass a type string and a DictionaryIO object to its constructor. The constructor uses these parameters to set its own properties. Here is how you might now instantiate a Dictionary object:

$en = new Dictionary( "En", new DictionaryIO() );

The Dictionary class is now much safer than before. You know that any Dictionary object will have been initialized with the required arguments.

Of course, there's no way yet to stop someone coming along later and changing the $type property or setting $dictio to null. Luckily, PHP V5 can help you there, too.



Keywords: Can we have a little privacy in here?

You have already seen the public keyword in relation to property declarations. This keyword denotes a property's visibility. In fact, the visibility of a property can be set to public, private, and protected. Properties that are public can be written to and read from outside the class. Properties that are private can only be seen within the object or class context. Properties that are protected can only be seen within the context of the current class or its children. (You will see this in action in the Inheritance section.) You can use private properties to really lock down our classes. If you declare your properties private and attempt to access them from outside the class' scope (as shown in Listing 7), the PHP engine will throw a fatal error.


Listing 7. Attempting to access your properties from outside the class' scope
                
class Dictionary {
private $translations = array();
private $dictio;
private $type;

function __construct( $type, DictionaryIO $dictio ) {
$this->type = $type;
$this->dictio = $dictio;
}

// ...
}

$en = new Dictionary( "En", new DictionaryIO() );
$en->dictio = null;

This outputs the following:

Fatal error: Cannot access private property 
Dictionary::$dictio in...

As a rule of thumb, you should make most properties private, then provide methods for getting and setting them if necessary. In this way, you can control a class' interface, making some data read-only, cleaning up or filtering arguments before assigning them to properties, and providing a clear set of rules for interacting with objects.

You can modify the visibility of methods in the same way as properties, adding public, private, or protected to the method declaration. If a class needs to use some housekeeping methods that the outside world need not know about, for example, you can declare them private. In Listing 8, a get() method provides the interface for users of the Dictionary class to extract a translation. The class also needs to keep track of all queries and provides a private method, logQuery(), for this purpose.


Listing 8. A get() method provides the interface for users of the Dictionary class
                
function get( $term ) {
$value = $this->translations[$term];
$this->logQuery( $term, $value, "get" );
return $value;
}

private function logQuery( $term, $value, $kind ) {
// write log information
}

Declaring logQuery() as private simplifies the public interface and protects the class from having logQuery() called inappropriately. As with properties, any attempt to call a private method from outside the containing class causes a fatal error.



Working in class context

The methods and properties you have seen so far all operate in object context. That is, you must access them using an object instance, via the $this pseudo-variable or an object reference stored in a standard variable. In some cases, you may find that it's more useful to access properties and methods via a class rather than an object instance. Class members of this kind are known as static.

To declare a static property, place the keyword static after the visibility modifier, directly in front of the property variable.

This example shows a single static property: $iodir, which holds the path to the default directory for saving and reading Dictionary data. Because this data is the same for all objects, it makes sense to make it available across all instances.


Listing 9. A single static $iodir property
                
class Dictionary {
public static $iodir=".";
// ...
}

You can access a static property using the scope resolution operator, which consists of a double colon (::). The scope resolution operator should sit between the class name and the static property you wish to access.

print Dictionary::$iodir . "\n";
Dictionary::$iodir = "/tmp";

As you can see, there is no need to instantiate a Dictionary object to access this property.

The syntax for declaring and accessing static methods is similar. Once again, you should place the static keyword after the visibility modifier. Listing 10 shows two static methods that access the $iodir property, which is now declared private.


Listing 10. Two static methods that access the $iodir property
                
class Dictionary {
private static $iodir=".";
// ...
public static function setSaveDirectory( $dir ) {
if ( ! is_dir( $dir ) ||
! is_writable( $dir ) ) {
return false;
}
self::$iodir = $dir;
}

public static function getSaveDirectory( ) {
return self::$iodir;
}
// ...
}

Users can no longer access the $iodir property directory. By creating special methods for accessing a property, you can ensure that any provided value is sane. In this case, the method checks that the given string points to a writable directory before making the assignment.

Notice that both methods refer to the $iodir property using the keywordself and the scope resolution operator. You cannot use $this in a static method because $this is a reference to the current object instance, but a static method is called via the class and not an object. If the PHP engine sees $this in a static method, it will throw a fatal error together with an informative message.

To call a static method from outside of its class, use the class name together with the scope resolution operator and the name of the method.

Dictionary::setSaveDirectory("/tmp");
print Dictionary::getSaveDirectory();

There are two good reasons why you might want to use a static method. First of all, a utility operation may not require an object instance to do its job. By declaring it static, you save client code the overhead of creating an object. Second, a static method is globally available. This means that you can set a value that all object instances can access, and it makes static methods a great way of sharing key data across a system.

While static properties are often declared private to prevent meddling, there is one way of creating a read-only statically scoped property: You can declare a constant. Like its global cousin, a class constant is immutable once defined. It is useful for status flags and for other things that don't change during the life of a process, like pi, for example, or all the countries in Africa.

You declare a class constant with the const keyword. For example, since a real-world implementation of a Dictionary object would almost certainly have a database sitting behind it, you can also assume that there will be a maximum length for terms and translations. Listing 11 sets this as a class constant.


Listing 11. Setting MAXLENGTH as a class constant
                
class Dictionary {
const MAXLENGTH = 250;
// ...
}

print Dictionary::MAXLENGTH;

Class constants are always public, so you can't use the visibility keywords. This is not a problem because any attempt to change the value will result in a parse error. Also notice that unlike regular properties, a class constant does not begin with the dollar sign.



Inheritance

If you're already in any way familiar with object-oriented programming, you'll know that I have been saving the best for last. The relationship between classes and the dynamic objects they generate allows for much flexibility in a system. Individual Dictionary objects encapsulate distinct sets of translation data, for example, yet the model for these varying entities is defined in the single Dictionary class.

Sometimes, though, you need to inscribe variation down at the class level. Remember the DictionaryIO class? To recap, it takes data from a Dictionary object, writes it to the file system, takes data from a file, and merges it back into a Dictionary object. Listing 12 shows a quick implementation that uses serialization to save and load Dictionary data.


Listing 12. A quick implementation using serialization
                
class Dictionary {
// ...

function asArray() {
return $this->translations;
}

function getType() {
return $this->type;
}

function export() {
$this->dictio->export( $this );
}

function import() {
$this->dictio->import( $this );
}
}

class DictionaryIO {

function path( Dictionary $dictionary, $ext ) {
$path = Dictionary::getSaveDirectory();
$path .= DIRECTORY_SEPARATOR;
$path .= $dictionary->getType().".$ext";
return $path;
}

function export( Dictionary $dictionary ) {
$translations = $dictionary->asArray();
file_put_contents( $this->path(
$dictionary, 'serial'),
serialize( $translations ) );
}

function import( Dictionary $dictionary ) {
$path = $this->path( $dictionary, 'serial' );
if ( ! is_file( $path ) ) return false;
$translations = unserialize(
file_get_contents( $path ) );
foreach ( $translations as $term => $trans ) {
$dictionary->set( $term, $trans );
}
}
}

$dict = new Dictionary( "En", new DictionaryIO() );
$dict->set( "TREE", "tree" );
$dict->export();

This example introduces a couple of simple Dictionary methods -- in particular, asArray(), which returns a copy of the $translations array. The DictionaryIO implementation has the virtue of simplicity. As is usual in example code, error checking has been omitted, but even so, this is a quick and easy way of saving data to file.

Once you have deployed a library of this sort, you soon become committed to supporting its save format. Making a format obsolete risks the goodwill of your users who may store backups in this way. But requirements change, and you may also get complaints that the output format is not easily user-editable. Such users may wish to send export files to third parties in XML format.

You now face a problem. How do you support both formats behind the DictionaryIO interface?

One solution would be to use a conditional statement inside the export() and import() methods that tests a type flag, as shown in Listing 13.


Listing 13. Using a conditional statement inside the export() and import() methods
                
function export( Dictionary $dictionary ) {
if ( $this->type == DictionaryIO::SERIAL ) {
// write serialized data
} else if ( $this->type == DictionaryIO::XML ) {
// write xml data
}
}

function import( Dictionary $dictionary ) {
if ( $this->type == DictionaryIO::SERIAL ) {
// read serialized data
} else if ( $this->type == DictionaryIO::XML ) {
// read xml data
}
}

This kind of structure is an example of a bad "code smell" in that it relies upon duplication. When a change in one place (adding a new type test, for example) requires a set of parallel changes in other places (bringing other type tests into line), code can quickly become error-prone and hard to read.

Inheritance offers a much more elegant solution. You can create a new class XmlDictionaryIO that inherits the interface laid down by DictionaryIO, but overrides some of its functionality.

You create a child class using the extends keyword. Here is a minimal implementation of the XmlDictionaryIO class:

XmlDictionaryIO extends DictionaryIO {
}

XmlDictionaryIO is now functionally identical to DictionaryIO. Because it inherits all public (and protected) attributes from DictionaryIO, you can do all the same things with an XmlDictionaryIO object that you can do with a DictionaryIO object. This relationship extends to object type. An XmlDictionaryIO object is obviously an instance of the XmlDictionaryIO class, but it is also an instance of DictionaryIO -- in the same way that a person is a human, a mammal, and an animal all at the same time and in that order of generalization. You can test this using the instanceof operator, which returns true if the object is a member of the indicated class, as shown in Listing 14.


Listing 14. Using the instanceof operator to test inheritance
                
$dictio = new XmlDictionaryIO();
if ( $dictio instanceof XmlDictionaryIO ) {
print "object is an instance of XmlDictionaryIO\n";
}

if ( $dictio instanceof DictionaryIO ) {
print "object is an instance of DictionaryIO\n";
}

This outputs:

object is an instance of XmlDictionaryIO
object is an instance of DictionaryIO

Just as instanceof accepts that $dictio is a DictionaryIO object, so, too, will methods accepting these objects as arguments. This means that an XmlDictionaryIO object can be passed to the Dictionary class' constructor, even though DictionaryIO is the type specified by the constructor's signature.

Listing 15 is a quick and dirty XmlDictionaryIO implementation that uses DOM for its XML functionality.


Listing 15. XmlDictionaryIO implementation
                
class XmlDictionaryIO extends DictionaryIO {

function export( Dictionary $dictionary ) {
$translations = $dictionary->asArray();
$doc = new DOMDocument("1.0");
$dic_el = $doc->createElement( "dictionary" );
$doc->appendChild( $dic_el );
foreach ( $translations as $key => $val ) {
$term_el = $doc->createElement( "term" );
$dic_el->appendChild( $term_el );
$key_el = $doc->createElement("key", $key );
$val_el = $doc->createElement(
"value", $val );
$term_el->appendChild( $key_el );
$term_el->appendChild( $val_el );
}
file_put_contents( $this->path(
$dictionary, 'xml'),
$doc->saveXML() );
}

function import( Dictionary $dictionary ) {
$path = $this->path( $dictionary, 'xml');
if ( ! is_file( $path ) ) return false;
$doc = DOMDocument::loadXML(
file_get_contents( $path ) );
$termlist = $doc
->getElementsByTagName( "term" );
foreach ( $termlist as $term ) {
$key = $term->getElementsByTagName( "key" )
->item( 0 )->nodeValue;
$val = $term
->getElementsByTagName( "value" )
->item( 0 )->nodeValue;
$dictionary->set( $key, $val );
}
}
}

The details of acquiring and generating XML can be taken for granted. There are plenty of ways of getting this done, including the excellent SimpleXML extension. In summary, the import() method takes an XML document and uses it to populate a Dictionary object. The export() method takes the data from a Dictionary object and writes it to an XML file. (In the real world, you would probably use an XML-based format called XLIFF, which is suitable for importing into third-party translation tools.)

Notice that both import() and export() call the utility method path(), which doesn't exist in the XmlDictionaryIO class. This doesn't matter because path() is implemented in DictionaryIO. When XmlDictionaryIO implements a method, it is this implementation that is invoked for an XmlDictionaryIO object when the method is called. When no implementation is present, the call falls through to the parent class.

Figure 2 shows the inheritance relationship between the DictionaryIO and XmlDictionaryIO classes. The closed arrow denotes inheritance and points from child to parent.


Figure 2. An inheritance relationship
inheritance relationship


Summary

With limited space available, it has not been possible to cover everything. There are two directions to take in further research: One should yield breadth and the other depth. By breadth, I mean the features that were beyond the scope of this article, such as abstract classes, interfaces, the iterator interface, reflection, exceptions, and object cloning. By depth, I mean questions of design. While it is important to understand the range of tools available in PHP for object-oriented programming, it is equally crucial to consider how best to work with such features. Fortunately, there are many resources available that focus on patterns of design in an object-oriented context (see Resources).

If you are still programming with PHP V4, I hope you found enough new features to justify migrating to V5 and its core object-oriented features. You'll soon wonder how you managed without them.



Just like any language, developers can write code in PHP that ranges in quality from truly awful to very good. Learn good programming habits that can help you bridge the productivity gap.

Depending on whom you ask, the difference between a good developer and an excellent developer, in terms of productivity, is a factor of 10 to 20. An excellent developer is more productive because of his experience and good habits. When poor programming habits sneak into your code, they're a drain on productivity. This article demonstrates some good programming habits that can make you a better programmer.

In addition to enabling you to build code more productively, these habits can help you build code sustainable for an application's lifetime. Any code you write is likely to spend most of its lifetime in maintenance; application maintenance is a large expense. Establishing good coding habits will enhance design factors like modularity, and your code will be easier to understand and, thus, easier and cheaper to maintain.

Bad coding habits seem to accompany defects in code and can cause code to be difficult to change without introducing new defects. The following five good habits, when applied to your PHP code, will help you avoid these pitfalls:

1. Use good naming.
2. Take smaller bites.
3. Document your code.
4. Handle error conditions.
5. Never, ever, copy and paste.

The next sections explain these habits in detail.

Use good naming

Using good naming is the most important habit because descriptive names make code easier to read and understand. The understandability of your code ultimately determines whether it can be maintained in the future. Even if the code you write contains no comments, if it's easy to understand, it will be much easier for you or someone else to change, if necessary. Your aim, when developing this practice, should be to use good naming to make your code read much like a book.

Bad habit: Ambiguous or meaningless names

Listing 1 shows code that includes overly short variable names, abbreviations that are difficult to understand, and method names that don't clearly describe what the methods do. Method names that imply the methods do one thing when they really do something else can be particularly problematic because they're misleading.

Listing 1. Bad: Ambiguous or meaningless names

 

function getNBDay($d)
{
switch($d) {
case 5:
case 6:
case 7:
return 1;
default:
return ($d + 1);
}
}

$day = 5;

$nextDay = getNBDay($day);

echo ("Next day is: " . $nextDay . "\n");

?>


Good habit: Reflective yet concise names

Listing 2 demonstrates code that uses good naming habits. Methods are renamed to be more reflective of what they do and why. Variables are renamed to be more descriptive, as well. The only variable that's left short is $i, which in this listing is a looping variable. Although many people may disagree, a short name for the looping variable is acceptable - even good - because it's a clear indicator of functionality.

Listing 2. Good: Reflective yet concise names

 

define ('MONDAY', 1);
define ('TUESDAY', 2);
define ('WEDNESDAY', 3);
define ('THURSDAY', 4);
define ('FRIDAY', 5);
define ('SATURDAY', 6);
define ('SUNDAY', 7);

/*
*
* @param $dayOfWeek
* @return int Day of week, with 1 being Monday and so on.
*/
function findNextBusinessDay($dayOfWeek)
{
$nextBusinessDay = $dayOfWeek;

switch($dayOfWeek) {
case FRIDAY:
case SATURDAY:
case SUNDAY:
$nextBusinessDay = MONDAY;
break;
default:
$nextBusinessDay += 1;
break;
}

return $nextBusinessDay;
}

$day = FRIDAY;

$nextBusDay = findNextBusinessDay($day);

echo ("Next day is:" . $nextBusDay . "\n");

?>


You are encouraged to break up large conditions into a method and name the method so it describes the condition. This technique makes the code easier to read and externalizes the condition so it can be abstracted and perhaps even reused. If the terms of the condition change, it's easier to update the method. Because the method has a meaningful name, the code doesn't lose its meaning or become difficult to read.


Take smaller bites

It's easy to get focused on solving a problem and start coding away. While you're solving an immediate problem, you keep typing, letting your functions get longer and longer. That's not a problem over the long term, as long as you go back later and refactor the code into smaller bites.

Refactoring is a great idea, but you should develop the habit of writing shorter, more focused methods the first time. Shorter methods that can be viewed in one window are easier to understand. When a method is too long to be viewed all at once in a window, it decreases in understandability because you can't quickly follow its entire flow from beginning to end.

When building methods, you should also form the habit of constructing them so they do one thing and one thing only. There are several reasons for such diligent focus in your method writing. First, methods are more easily reused when they do one thing and do it well. Second, such methods are easier to test. Third, such methods are easier to understand and change - if necessary - the simpler they are.

Bad habit: Really long functions (that do a lot)

Listing 3 shows a long function. It's problematic for a couple of other reasons. It does many things, so it isn't cohesive. It will be harder to understand, debug, and test. It iterates through a file and builds a list of entries, it assigns the values to objects, it does some calculations, and more.

Listing 3. Bad: Long functions

 

function writeRssFeed($user)
{
// Get the DB connection information


// look up the user's preferences...
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());

// Query
$perfsQuery = sprintf("SELECT max_stories FROM user_perfs WHERE user= '%s'",
mysql_real_escape_string($user));

$result = mysql_query($query, $link);

$max_stories = 25; // default it to 25;

if ($row = mysql_fetch_assoc($result)) {
$max_stories = $row['max_stories'];
}

// go get my data
$perfsQuery = sprintf("SELECT * FROM stories WHERE post_date = '%s'",
mysql_real_escape_string());

$result = mysql_query($query, $link);


$feed = "" .
"" .
"My Great Feed" .
"http://www.example.com/feed.xml" .
"The best feed in the world" .
"en-us" .
"Tue, 20 Oct 2008 10:00:00 GMT" .
"Tue, 20 Oct 2008 10:00:00 GMT" .
"http://www.example.com/rss" .
"MyFeed Generator" .
"editor@example.com" .
"webmaster@example.com" .
"5";

// build the feed...
while ($row = mysql_fetch_assoc($result)) {
$title = $row['title'];
$link = $row['link'];
$description = $row['description'];
$date = $row['date'];
$guid = $row['guid'];

$feed .= "";
$feed .= "" . $title . "";
$feed .= "" . $link . "";
$feed .= " " . $description . "";
$feed .= "" . $date . "";
$feed .= "" . $guid . "";
$feed .= "
";
}

$feed .= "

// write the feed out to the server...
echo($feed);

}

?>


If you add more to this method, it will soon become virtually unmaintainable.

Good habit: Manageable, focused functions

Listing 4 demonstrates a more concise, more readable rewrite of the original method. In this example, the long method has been broken into smaller methods that each do one thing and do it well. The result will be more reusable in the future and will be easier to test.

Listing 4. Good: Manageable, focused functions

 

function createRssHeader()
{
return "" .
"" .
"My Great Feed" .
"http://www.example.com/feed.xml" .
"The best feed in the world" .
"en-us" .
"Tue, 20 Oct 2008 10:00:00 GMT" .
"Tue, 20 Oct 2008 10:00:00 GMT" .
"http://www.example.com/rss" .
"MyFeed Generator" .
"editor@example.com" .
"webmaster@example.com" .
"5";
}

function createRssFooter()
{
return "";
}

function createRssItem($title, $link, $desc, $date, $guid)
{
$item .= "";
$item .= "" . $title . "";
$item .= "" . $link . "";
$item .= " " . $description . "";
$item .= "" . $date . "";
$item .= "" . $guid . "";
$item .= "
";
return $item;
}

function getUserMaxStories($db_link, $default)
{
$perfsQuery = sprintf("SELECT max_stories FROM user_perfs WHERE user= '%s'",
mysql_real_escape_string($user));

$result = mysql_query($perfsQuery, $db_link);

$max_stories = $default;

if ($row = mysql_fetch_assoc($result)) {
$max_stories = $row['max_stories'];
}

return $max_stories;
}

function writeRssFeed($user)
{
// Get the DB connection information
$settings = parse_ini_file("rss_server.ini");

// look up the user's preferences...
$link = mysql_connect($settings['db_host'], $settings['user'],
$settings['password']) OR die(mysql_error());

$max_stories = getUserMaxStories($link, 25);

// go get my data
$newsQuery = sprintf("SELECT * FROM stories WHERE post_date = '%s'",
mysql_real_escape_string(time()));

$result = mysql_query($newsQuery, $link);

$feed = createRssHeader();

$i = 0;
// build the feed...
while ($row = mysql_fetch_assoc($result)) {
if ($i < $max_stories) {
$title = $row['title'];
$link = $row['link'];
$description = $row['description'];
$date = $row['date'];
$guid = $row['guid'];

$feed .= createRssItem($title, $link, $description, $date, $guid);

$i++;
} else {
break;
}
}

mysql_close($link);

$feed .= createRssFooter();

// write the feed out to the server...
echo($feed);
}
?>


Breaking down longer methods can offer diminishing returns, so be careful that when introducing this good habit you don't overdo it. It's possible to break up code so much that it's as difficult to read as it was when it was all one monolithic function.


Document your code

Documenting your code well sometimes seems as difficult as writing it in the first place. Knowing what to document is tricky because it's tempting to document what the code is doing. Documenting the code's intention is a better idea. In the header blocks of functions that may not be obvious, tell the reader the expected inputs and outputs of the methods and the original intent.

Documenting what the code is doing is common, but unnecessary. If the code is so confusing that you have to document what it's doing, take that as a hint that you should rewrite the code to make it easier to understand. Develop the habit of using good naming and smaller methods and structures to make your code more readable without having to comment what it does.

Bad habit: Missing and redundant function documentation

The comments in Listing 5 merely tell the reader what the code is doing - that it's iterating through a loop or that it's adding a number. But what is missing is why it's doing what it's doing. It would be difficult for someone maintaining this code to know whether the code can be safely changed without introducing new defects.

Listing 5. Bad: Missing and redundant function documentation

 

class ResultMessage
{
private $severity;
private $message;

public function __construct($sev, $msg)
{
$this->severity = $sev;
$this->message = $msg;
}

public function getSeverity()
{
return $this->severity;
}

public function setSeverity($severity)
{
$this->severity = $severity;
}

public function getMessage()
{
return $this->message;
}

public function setMessage($msg)
{
$this->message = $msg;
}
}

function cntMsgs($messages)
{
$n = 0;
/* iterate through the messages... */
foreach($messages as $m) {
if ($m->getSeverity() == 'Error') {
$n++; // add one to the result;
}
}
return $n;
}

$messages = array(new ResultMessage("Error", "This is an error!"),
new ResultMessage("Warning", "This is a warning!"),
new ResultMessage("Error", "This is another error!"));

$errs = cntMsgs($messages);

echo("There are " . $errs . " errors in the result.\n");

?>


Good habit: Documented functions and classes

The comments in Listing 6 tell the reader the intentions of the classes and methods. The comments tell why the functions are doing what they're doing, which will be much more helpful in the future when the code is being maintained. Conditions may change that require your code to be modified, and that's an easier task if it's simple to find out what your code's purpose was in the first place.

Listing 6. Good: Documented functions and classes

/**
* The ResultMessage class holds a message that can be returned
* as a result of a process. The message has a severity and
* message.
*
* @author nagood
*
*/
class ResultMessage
{
private $severity;
private $message;

/**
* Constructor for the ResultMessage that allows you to assign
* severity and message.
* @param $sev See {@link getSeverity()}
* @param $msg
* @return unknown_type
*/
public function __construct($sev, $msg)
{
$this->severity = $sev;
$this->message = $msg;
}

/**
* Returns the severity of the message. Should be one
* "Information", "Warning", or "Error".
* @return string Message severity
*/
public function getSeverity()
{
return $this->severity;
}

/**
* Sets the severity of the message
* @param $severity
* @return void
*/
public function setSeverity($severity)
{
$this->severity = $severity;
}

public function getMessage()
{
return $this->message;
}

public function setMessage($msg)
{
$this->message = $msg;
}
}


/*
* Counts the messages with the given severity in the array
* of messages.
*
* @param $messages An array of ResultMessage
* @return int Count of messages with a severity of "Error"
*/
function countErrors($messages)
{
$matchingCount = 0;
foreach($messages as $m) {
if ($m->getSeverity() == "Error") {
$matchingCount++;
}
}
return $matchingCount;
}

$messages = array(new ResultMessage("Error", "This is an error!"),
new ResultMessage("Warning", "This is a warning!"),
new ResultMessage("Error", "This is another error!"));

$errs = countErrors($messages);

echo("There are " . $errs . " errors in the result.\n");

?>

 


Handle errors

It's been said that when you're writing robust applications, error-handling code seems to follow the 80/20 rule: 80 percent of the code is dedicated to handling exceptions and validations, and 20 percent of the code does the actual work. It's natural when writing code to do happy-path coding. This means writing code that works well for the basic conditions, when all the data is valid and all the conditions are as expected. But such code can be fragile over the application's lifetime. At the other extreme, you may spend too much time writing code for conditions that may never be encountered.

This habit is about finding the balance between doing enough error handling and not doing so much gold plating that your code is never finished.

Bad habit: Not handling errors at all

The code in Listing 7 demonstrates a couple of bad habits. One is not checking the parameters coming in, even though you know at this point that a parameter in a certain state will cause an exception in your method. The second is that the code calls a method that can throw an exception without handling it. This code will leave the author or maintainer to make guesses about the source of the problem - when problems start occurring.

Listing 7. Bad: Not handling error conditions

 

// Get the actual name of the
function convertDayOfWeekToName($day)
{
$dayNames = array(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday");
return $dayNames[$day];
}

echo("The name of the 0 day is: " . convertDayOfWeekToName(0) . "\n");
echo("The name of the 10 day is: " . convertDayOfWeekToName(10) . "\n");
echo("The name of the 'orange' day is: " . convertDayOfWeekToName('orange') . "\n");

?>


Good habit: Programming defensively

Listing 8 demonstrates handling and throwing exceptions in a meaningful way. Not only does the additional error handling make the code more robust, but it also helps with readability and understandability. The way the exceptions are handled provides a good indication of what the original author was looking for when the method was written.

Listing 8. Good: Programming defensively

 

/**
* This is the exception thrown if the day of the week is invalid.
* @author nagood
*
*/
class InvalidDayOfWeekException extends Exception { }

class InvalidDayFormatException extends Exception { }

/**
* Gets the name of the day given the day in the week. Will
* return an error if the value supplied is out of range.
*
* @param $day
* @return unknown_type
*/
function convertDayOfWeekToName($day)
{
if (! is_numeric($day)) {
throw new InvalidDayFormatException('The value \'' . $day . '\' is an ' .
'invalid format for a day of week.');
}

if (($day > 6) || ($day < 0)) {
throw new InvalidDayOfWeekException('The day number \'' . $day . '\' is an ' .
'invalid day of the week. Expecting 0-6.');
}

$dayNames = array(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday");
return $dayNames[$day];
}

echo("The name of the 0 day is: " . convertDayOfWeekToName(0) . "\n");

try {
echo("The name of the 10 day is: " . convertDayOfWeekToName(10) . "\n");
} catch (InvalidDayOfWeekException $e) {
echo ("Encountered error while trying to convert value: " . $e->getMessage() . "\n");
}

try {
echo("The name of the 'orange' day is: " . convertDayOfWeekToName('orange') . "\n");
} catch (InvalidDayFormatException $e) {
echo ("Encountered error while trying to convert value: " . $e->getMessage() . "\n");
}

?>


Although checking parameters is validation - and it's helpful to anyone using your functions if you require parameters to be a certain way - you should check them and throw meaningful exceptions:

* Handle exceptions as near to the problem as possible.
* Handle each exception specifically.



Never, ever copy and paste

The ability to copy code from one place and paste it into your code editor is a double-edged sword. On one hand, it saves a lot of errors when you're retyping from an example or a template. On the other hand, it makes proliferation of similar code way too easy.

Be on your guard against copying and pasting code between parts of your application. When you find yourself doing it, stop and ask yourself how you could rewrite the section of code you're copying to be something that you can reuse. Putting code in one place allows you to more easily maintain your code, to a large degree, because changes need to be made in only one place.

Bad habit: Similar sections of code

Listing 9 shows a couple of methods that are nearly identical, except for a couple of values here and there. Tools are available to help you find copied and pasted code (see Resources).

Listing 9. Bad: Similar sections of code

/**
* Counts the number of messages found in the array of
* ResultMessage with the getSeverity() value of "Error"
*
* @param $messages An array of ResultMessage
* @return unknown_type
*/
function countErrors($messages)
{
$matchingCount = 0;
foreach($messages as $m) {
if ($m->getSeverity() == "Error") {
$matchingCount++;
}
}
return $matchingCount;
}

/**
* Counts the number of messages found in the array of
* ResultMessage with the getSeverity() value of "Warning"
*
* @param $messages An array of ResultMessage
* @return unknown_type
*/
function countWarnings($messages)
{
$matchingCount = 0;
foreach($messages as $m) {
if ($m->getSeverity() == "Warning") {
$matchingCount++;
}
}
return $matchingCount;
}

/**
* Counts the number of messages found in the array of
* ResultMessage with the getSeverity() value of "Information"
*
* @param $messages An array of ResultMessage
* @return unknown_type
*/
function countInformation($messages)
{
$matchingCount = 0;
foreach($messages as $m) {
if ($m->getSeverity() == "Information") {
$matchingCount++;
}
}
return $matchingCount;
}

$messages = array(new ResultMessage("Error", "This is an error!"),
new ResultMessage("Warning", "This is a warning!"),
new ResultMessage("Error", "This is another error!"));

$errs = countErrors($messages);

echo("There are " . $errs . " errors in the result.\n");
?>


Good habit: Reusable functions with parameters

Listing 10 shows the code modified to put the copied code into one method. The other methods have been changed to delegate the work to the new method. Building the common method takes some design time, and certainly doing so makes you pause and think instead of instinctively using the copy-and-paste shortcut key combinations. But you'll get back the time you invested the first time the common code needs to be changed.

Listing 10. Good: Reusable functions with parameters

/*
* Counts the messages with the given severity in the array
* of messages.
*
* @param $messages An array of ResultMessage
* @return int Count of messages matching $withSeverity
*/
function countMessages($messages, $withSeverity)
{
$matchingCount = 0;
foreach($messages as $m) {
if ($m->getSeverity() == $withSeverity) {
$matchingCount++;
}
}
return $matchingCount;
}

/**
* Counts the number of messages found in the array of
* ResultMessage with the getSeverity() value of "Error"
*
* @param $messages An array of ResultMessage
* @return unknown_type
*/
function countErrors($messages)
{
return countMessages($messages, "Errors");
}

/**
* Counts the number of messages found in the array of
* ResultMessage with the getSeverity() value of "Warning"
*
* @param $messages An array of ResultMessage
* @return unknown_type
*/
function countWarnings($messages)
{
return countMessages($messages, "Warning");
}

/**
* Counts the number of messages found in the array of
* ResultMessage with the getSeverity() value of "Warning"
*
* @param $messages An array of ResultMessage
* @return unknown_type
*/
function countInformation($messages)
{
return countMessages($messages, "Information");
}

$messages = array(new ResultMessage("Error", "This is an error!"),
new ResultMessage("Warning", "This is a warning!"),
new ResultMessage("Error", "This is another error!"));

$errs = countErrors($messages);

echo("There are " . $errs . " errors in the result.\n");

?>



Conclusion

If you develop the good habits discussed in this article while developing your PHP code, you'll build code that is easy to read, understand, and maintain. Building easily maintainable code in this manner will enable you to debug, fix, and extend your code with lower risk.

Using good naming and organizing your code into smaller prices makes your code easier to read. Documenting the purpose of your code makes its intent easier to understand and extend. Handling errors properly makes your code more robust. Finally, breaking the crutch of copying and pasting lets you keep your code clean.



Extensible Markup Language (XML) is a general purpose specification for creating custom markup languages. XML is classified as an extensible language, because it allows the user to define the mark-up elements. XML's purpose is to aid information systems in sharing structured data, especially via the Internet, to encode documents, and to serialize data; in the last context, it compares with text-based serialization languages such as JSON and YAML.

XML is recommended by the World Wide Web Consortium (W3C). It is a free open standard. XML is a markup language for documents containing structured information.

Structured information contains both content (words, pictures, etc.) and some indication of what role that content plays (for example, content in a section heading has a different meaning from content in a footnote, which means something different than content in a figure caption or content in a database table, etc.). Almost all documents have some structure.

A markup language is a mechanism to identify structures in a document. The XML specification defines a standard way to add markup to documents.



JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

 

var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};

 

In this example, an object is created containing a single member "bindings", which contains an array containing three objects, each containing "ircEvent", "method", and "regex" members.

Members can be retrieved using dot or subscript operators.

myJSONObject.bindings[0].method // "newURI"

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

var myObject = eval('(' + myJSONtext + ')');

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

JSON Schema

There are several ways to verify the structure and data types inside a JSON object, much like an XML schema. JSON Schema is a specification for a JSON-based format for defining the structure of JSON data. JSON Schema provides a contract for what JSON data is required for a given application and how it can be modified, much like what XML Schema provides for XML. JSON Schema is intended to provide validation, documentation, and interaction control of JSON data. JSON Schema is based on the concepts from XML Schema, RelaxNG, and Kwalify, but is intended to be JSON-based, so that JSON data in the form of a schema can be used to validate JSON data, the same serialization/deserialization tools can be used for the schema and data, and it can be self descriptive. Json.Com. "JSON Schema Proposal".

Security issues

Although JSON is intended as a data serialization format, its design as a subset of the JavaScript programming language poses several security concerns. These concerns center on the use of a JavaScript interpreter to dynamically execute JSON text as JavaScript, thus exposing a program to errant or malicious script contained therein -- often a chief concern when dealing with data retrieved from the internet. While not the only way to process JSON, it is an easy and popular technique, stemming from JSON's design to be compatible with JavaScript's eval() function.



ExtJS Web 2.0

Posted by: manishmt

Tagged in: web 2.0 , RIA , Open Source , Javascript , Ajax

manishmt
I come accross ExtJS web 2.0 library to create Rich Internet Application (RIA) , and I am highly impressed with this library.

About ExtJS : It is a cross-browser java-script library that allows for building the Rich Internet Applications (RIA).
Offical Website : extjs.com
It includes:

* High performance, customizable UI widgets
* Well designed and extensible Component model
* An intuitive, easy to use API
* Commercial and Open Source licenses available


Ext uses the latest web 2.0 methods, such as Ajax, which has built in parsers for XML (Extensible Markup Language), JSON (JavaScript Object Notation), Text and few other formats. Using ExtJS user can create desktop looking interfaces with just som simple notation(ExtJS is probably not the first project to do this)...this in my opinion is one of the greatest things ExtJS has to offer. The simple notation way of creating these interfaces allows for rapid deployment of interfaces, and takes the GUI (Graphical User Interface) creation out of the hands of the developer, and allows the developer to focus on getting the data to the front end.

ExtJS recently release of Ext 2.2 version and it supports all the major web browser (Internet Explorer 6+, FireFox 1.5+, Safari 3+, Opera 9+)

Currently Ext documentation is not very good but the community is very active. In my opinion the Ext documentation could take a lesson from the PHP documentation and add common examples in this notation style format, for the various things you may want to do with an object/widget/datastore.

Conclusion: ExtJS is very good product with a bright future and just needs to improve its documentation as well as it has its interface objects.



Free - Magazines

My Tweets

more info...!

Take a Poll

Best source to get open source developers?

Chat

Please login to be able to chat.

Feed Subscription

Enter your email address:

Delivered by FeedBurner

Feedback Form