Thursday, December 27, 2007

PHP Advanced Tutorials Collection

Php advanced tutorials collection . tutorials about ajax , zend framework , widgets , how to write a search engine with php , caching with php and more .

read more | digg story

Tuesday, September 18, 2007

Object Oriented Programming in PHP: The Way to Large PHP Projects

This arcticle introduces Object Oriented Programming (OOP) in PHP. I will show you how to code less and better by using some OOP concepts and PHP tricks. Good luck!
Concepts of object oriented programming: There're differences between authors, I can mention that a OOP language must have:
  • Abstract data types and information hidding
  • Inheritance
  • Polymorphism
The encapsulation is done in php using classes:


class Something {
// In OOP classes are usually named starting with a cap letter.
var $x;

function
setX($v) {
// Methods start in lowercase then use lowercase to seprate
// words in the method name example getValueOfArea()
$this->x=$v;
}

function
getX() {
return
$this->x;
}
}

?>
Of course you can use your own nomenclature, but having a standarized one is useful.
Data members are defined in php using a "var" declaration inside the class, data members have no type until they are assigned a value. A data member might be an integer, an array, an associative array or even an object. Methods are defined as functions inside the class, to access data members inside the methods you have to use $this->name, otherwise the variable is local to the method.
You create an object using the new operator:
$obj=new Something;
Then you can use member functions by:
$obj->setX(5);
$see=$obj->getX();
The setX member function assigns 5 to the x datamember in the object obj (not in the class), then getX returns its value: 5 in this case.
You can access the datamembers from the object reference using for example: $obj->x=6; however, this is not a very good OOP practice. I enforce you to set datamembers by defining methods to set them and access the datamembers by using retrieving methods. You'll be a good OOP programmer if you consider data members inaccesible and only use methods from the object handler. Unfortunately PHP doesn't have a way to declare a data member private so bad code is allowed.
Inheritance is easy in php using the extend keyword.


class Another extends Something {
var
$y;
function
setY($v) {
// Methods start in lowercase then use lowercase to seperate
// words in the method name example getValueOfArea()
$this->y=$v;
}

function
getY() {
return
$this->y;
}
}

?>
Objects of the class "Another" now has all the data members and methods of the parent class (Something) plus its own data members and methods. You can use:
$obj2=new Something;
$obj2->setX(6);
$obj2->setY(7);
Multiple inheritance is not supported so you can't make a class extend two or more different classes.
You can override a method in the derived class by redefining it, if we redefine getX in "Another" we can't no longer access method getX in "Something". If you declare a data member in a derived class with the same name as a data member in a Base class the derived data member "hides" the base class data member when you access it.
You might define constructors in your classes, constructors are methods with the same name as the class and are called when you create an object of the class for example:


class Something {
var
$x;

function
Something($y) {
$this->x=$y;
}

function
setX($v) {
$this->x=$v;
}

function
getX() {
return
$this->x;
}
}

?>
So you can create an object by:
$obj=new Something(6);
And the constructor automatically asigns 6 to the data member x. Constructors and methods are normal php functions so you can use default arguments.
function Something($x="3",$y="5")
Then:
$obj=new Something();    // x=3 and y=5
$obj=new Something(8); // x=8 and y=5

When an object of a derived class is created only its constructor is called, the constructor of the Parent class is not called, this is a gotcha of PHP because constructor chaining is a classic feature of OOP, if you want to call the base class constructor you have to do it explicitely from the derived class constructor.It works because all methods of the parent class are available at the derived class due to inheritance.


function Another() {
$this->y=5;
$this->Something(); //explicit call to base class constructor.
}

?>
A nice mechanism in OOP is to use Abstract Classes, abstract classes are classes that are not instanciable and has the only purpose to define an interface for its derived classes. Designers often use Abstract classes to force programmers to derive classes from certain base classes so they can be certain that the new classes have some desired functionality. There's no standard way to do that in PHP but:
If you do need this feature define the base class and put a "die" call in its constructor so you can be sure that the base class is not instanciable, now define the methods (interface) putting "die" statements in each one, so if in a derived class a programmer doesn't override the method then an error raises. Furthermore you might need to be sure since php has no types that some object is from a class derived from you base class, then add a method in the base class to identify the class (return "some id"), and verify this when you receive an object as an argument. Of course this doesn't work if the evil programmer oveerides the method in the derived class but genrally the problem is dealing with lazy programmers no evil ones! Of course is better to keep the base class unreachable from the programmers, just print the interface and make them work!
There're no destructors in PHP.

$obj=new Something(8,9); // x=8 and y=9
Default arguments are used in the C++ way so you can't pass a value to Y and let X take the default value, arguments are asigned form left to right and when no more arguments are found if the function expected more they take the default values.

Overloading (which is different from overriding) is not supported in PHP. In OOP you "overload" a method when you define two/more methods with the same name but different number or type of parameters (depending upon the language). Php is a loosely typed language so overloading by types won't work, however overloading by number of parameters doesn't work either.
It's very nice sometimes in OOP to overload constructors so you can build the object in different ways (passing different number of arguments). A trick to do something like that in PHP is:


class Myclass {
function
Myclass() {
$name="Myclass".func_num_args();
$this->$name();
//Note that $this->$name() is usually wrong but here
//$name is a string with the name of the method to call.
}

function
Myclass1($x) {
code;
}
function
Myclass2($x,$y) {
code;
}
}

?>
With this extra working in the class the use of the class is transparent to the user:
$obj1=new Myclass('1');      //Will call Myclass1
$obj2=new Myclass('1','2'); //Will call Myclass2
Sometimes this is very nice.

Polymorphism
Polymorphism is defined as the ability of an object to determine which method to invoke for an object passed as argument in runtime time. For example if you have a class figure which defines a method draw and derived classes circle and rectangle where you override the method draw you might have a function which expects an argument x and then call $x->draw(). If you have polymorphism the method draw called depends of the type of object you pass to the function. Polymorphism is very easy and natural in interpreted languages as PHP (try to imagine a C++ compiler generating code for this case, which method do you call? You don't know yet which type of object you have!, ok this is not the point). So PHP happily supports polymorphism.


function niceDrawing($x) {
//Supose this is a method of the class Board.
$x->draw();
}

$obj=new Circle(3,187);
$obj2=new Rectangle(4,5);

$board->niceDrawing($obj); //will call the draw method of Circle.
$board->niceDrawing($obj2); //will call the draw method of Rectangle.

?>
OOP Programming in PHP
Some "purists" will say PHP is not truly an object oriented language, which is true. PHP is a hybrid language where you can use OOP and traditional procedural programming. For large projects, however, you might want/need(?) to use "pure" OOP in PHP declaring classes, and using only objects and classes for your project. As larger and larger projects emerge the use of OOP may help, OOP code is easy to mantain, easy to understand and easy to reuse. Those are the foundations of software engineering. Applying those concepts to web based projects is the key to success in future web sites.
Advanced OOP Techniques in PHP
After reviewing the basic concepts of OOP I can show you some more advanced techniques:
Serializing
PHP doesn't support persistent objects, in OOP persistent objects are objects that keep its state and funcionality across multiple invocations of the application, this means having the ability of saving the object to a file or database and then loading the object back. The mechanism is known as serialization. PHP has a serialize method which can be called for objects, the serialize method returns a string representation of the object. However serialize saves the datamembers of the object but not the methods.
In PHP4 if you serialize the object to string $s, then destroy the object, and then unserialize the object to $obj you might still access the object methods! I don't recommend this because (a) The documentation doesn't guarrantee this beahaviour so in future versions it might not work. (b) This might lead to 'illusions' if you save the serialized version to disk and exit the script. In future runs of the script you can't unserialize the string to an object an expect the methods to be there because the string representation doesn't have the methods! Summarizing serializing in PHP is VERY useful to save the data members of an object just that. (You can serialize asociative arrays and arrays to save them to disk too).
Example:


$obj
=new Classfoo();
$str=serialize($obj);
// Save $str to disk

//...some months later

//Load str from disk
$obj2=unserialize($str)

?>
You have the datamembers recovered but not the methods (according to the documentation). This leads to $obj2->x as the only way to access the data members (you have no methods!) so don't try this at home.
There're some ways to fix the problem, I leave it up to you because they are too dirty for this neat article.
Full serialization is a feature I'd gladly welcome in PHP.


Why PHP 5 Rocks!

PHP 5, which was released earlier this week, is the first major release of PHP in years to focus on new features.

While one of the key goals behind PHP 3 was increasing PHP/FI 2.0's performance and efficiency, at the same time it introduced a whole new set of functionality.

That was back in 1998.

PHP 4 provided another speed burst, as it introduced the Zend Engine. However, the majority of PHP 4's changes were behind the scenes. Those features allowed more people than ever to use PHP, but it didn't provide them with more tools to build their sites.

Finally, after six years, the community has revisited the legacy baggage that made tackling some problems unnecessarily difficult.

In particular, PHP 4's version of object-oriented programming (OOP) lacks many features, the MySQL extension doesn't support the new MySQL 4.1 client protocol, and XML support is a hodgepodge.

Fortunately, PHP 5 improves on PHP 4 in three major areas:

  • Object-oriented programming
  • MySQL
  • XML

These items have all been completely rewritten, turning them from limitations into star attractions. While these changes alone warrant a new version of PHP, PHP 5 also provides a plethora of other new features.

In this article, I highlight seven of my favorite PHP 5 features. These features allow your PHP 5 code to frequently be shorter, more elegant, and more flexible than ever before.

1. Robust Support for Object-Oriented Programming

Ever since Zeev and Andi's late-night OOP hack, PHP programmers have clamored for an increasing amount of OO features. However, neither PHP 3 nor PHP 4 truly incorporates objects into its core.

With PHP 5, PHP programmers can at last stop apologizing for PHP's krufty OO support. It offers:

  • Constructors
  • Destructors
  • Public, protected, and private properties and methods
  • Interfaces
  • Abstract classes
  • Class type hints
  • Static properties and methods
  • Final properties and methods
  • A whole suite of magical methods

Additionally, objects are now both assigned--and passed--by reference instead of by value, so the necessity to liberally sprinkle ampersands throughout your code is no more.

If you're a person who enjoys web programming using objects and patterns, then these features alone will make your year. However, PHP 5's just getting started.

2. A Completely Rewritten MySQL Extension

The MySQL database is PHP's partner in crime. Many developers power their web sites with MySQL, yet the MySQL extension is showing its age. In retrospect, some design decisions weren't the best solutions after all.

Also, the latest versions of MySQL, 4.1 and 5.0, introduce many new features, some of which require significant changes to the extension. As a result, PHP 5 comes with a completely new and improved MySQL extension. Dubbed MySQLi, for MySQL Improved. It offers:

  • Prepared statements
  • Bound input and output parameters
  • SSL connections
  • Multi-query functions

MySQLi even takes advantage of PHP 5's new object-oriented support to provide an OO interface to MySQL. On top of that, the latest versions of MySQL now enable subselects, transactions, and replication.

3. A Suite of Interoperable XML Tools

PHP 5 fixes the major problems in PHP 4's XML extensions. While PHP 4 allows you to manipulate XML, its XML tools are only superficially related. Each tool covers one part of the XML experience, but they weren't designed to work together, and PHP 4 support for the more advanced XML features is often patchy.

Not so in PHP 5.

The new XML extensions:

  • Work together as a unified whole.
  • Are standardized on a single XML library: libxml2.
  • Fully comply with W3 specifications.
  • Efficiently process data.
  • Provide you with the right XML tool for your job.

Additionally, following the PHP tenet that creating web applications should be easy, there's a new XML extension that makes it simple to read and alter XML documents. The aptly named SimpleXML extension allows you to interact with the information in an XML document as though these pieces of information are arrays and objects, iterating through them with for-each loops, and editing them in place merely by assigning new values to variables.

In short, SimpleXML kicks ass!

If you know the document's format ahead of time, such as when you're parsing RSS files, REST results, and configuration data, SimpleXML is the way to go.

And if you're a DOM fan, you'll be pleasantly surprised with PHP 5's DOM extension, which is light-years beyond what you're using in PHP 4.

4. An Embedded Database with SQLite

While MySQL is greater than ever, it's actually "too much database" for some jobs. SQLite is an embedded database library that lets you store and query data using an SQL interface without the overhead of installing and running a separate database application.

When your application needs a server-side storage mechanism but you can't rely upon the presence of a specific database, turn to SQLite. It correctly handles locking and concurrent accesses, the two big headaches with homebrewed flat files.

PHP 5 bundles SQLite, providing developers with a database that's guaranteed to work on all PHP 5 installations. Despite the name, SQLite is nowhere close to a "lite" database. It supports:

  • Transactions
  • Subqueries
  • Triggers
  • And many other advanced database features

You can even write user-defined functions in PHP and call them from within SQLite. This is by far and away the coolest feature available in any PHP database extension.

5. Cleaner Error Handling with Exceptions

PHP 5 offers a completely different model of error checking than what's available in PHP 4. It's called exception handling. With exceptions, you're freed from the necessity of checking the return value of every function. Instead, you can separate programming logic from error handling and place them in adjoining blocks of code.

Exceptions are commonly found in object-oriented languages such as Java and C++. When used judiciously, they streamline code, but when used willy-nilly, they create spaghetti code.

Right now, only a few PHP extensions use exceptions, but they're slowly being phased in. However, they're available today for any PHP code you write.

6. A First-Class SOAP Implementation

SOAP is a key component of the fast-growing web services field. This extension lets developers create SOAP clients with or without a Web Services Description Language (WSDL) file, and also implement SOAP servers in PHP.

PHP 4's SOAP support is only fair. While there are a few SOAP packages, the most mature ones are written in PHP instead of C. Therefore, they are slow, and you have to download and install them yourself.

With PHP 5, there's finally a usable SOAP extension written in C. Currently, this extension implements most, but not all, of SOAP 1.2. This is a significant improvement over previous C extension, and future pieces will be added in time.

Particularly in comparison with .NET and Java, PHP's SOAP support has always lagged behind the curve. Whether you love or hate SOAP, PHP needs to offer a first-class SOAP extension, and I'm excited to finally see some momentum in this direction.

7. Iterators

Iterators are a completely new PHP 5 feature. They allow you to use a for-each loop to cycle through different types of data: directory listings, database results, and even XML documents. SPL -- Standard PHP Library -- is a collection of iterators that provide this functionality and also filter, limit, cache, and otherwise modify iterator results.

Iterators are an incredibly handy way to abstract away messy details from your code.

For example, the DirectoryIterator turns directory iteration from this:


$dir = opendir($path);
while (false !== ($file = readdir($dir))) {
print "$file\n";
}
closedir($dir);

Into this:


foreach (new DirectoryIterator($path) as $file) {
print "$file\n";
}

There are no directory handles to mess about with, nor ugly conditions to check inside a while loop.

These are my top seven favorite features of PHP 5, but they're by no means the only ones. Besides what I've already highlighted, PHP 5 also offers:

  • Enhanced streams, wrappers, and filters.

    First introduced in PHP 4.3, streams are an underutilized part of PHP. They allow you to place a file interface on reading and writing data using protocol-specific objects known as wrappers. Streams also let you modify the data flowing through them by attaching filters.

  • Code introspection using the Reflection classes.

    This set of classes lets you examine classes, methods, parameters, and more, to discover object attributes. It is now simple and easy to create PHP class browsers, debuggers, and other tools that rely on gathering details about objects and functions.

  • Compliant HTML output thanks to Tidy.

    The Tidy extension makes it easy to ensure that your output is valid HTML and XHTML. Its smart parser brings even the most unruly of files into compliance with the latest W3C specifications.

  • Superior command-line processing.

    The PHP5 command-line version now allows individual line processing, similar to Perl and awk. You can specify code to be run at the beginning, on, and at the end of each line in a file.

I hope you've found this quick tour around PHP 5 useful. As you can see, PHP 5 is leaps and bounds better than before. I'm sure you'll find all sorts of cool ways to incorporate its features into your programs.

Adam Trachtenberg is the manager of technical evangelism for eBay and is the author of two O'Reilly books, "Upgrading to PHP 5" and "PHP Cookbook." In February he will be speaking at Web Services Edge 2005 on "Developing E-Commerce Applications with Web Services" and at the O'Reilly booth at LinuxWorld on "Writing eBay Web Services Applications with PHP 5."

Tuesday, September 11, 2007

5 tools every PHP programmer should know about

After working on several large scale PHP projects, and writing a lot of PHP code, I’ve discovered a number of tools that improve code quality, streamline rollouts, and generally make life as a PHP developer a whole lot easier. Many of these tools probably deserve a post of their own. But, since some people aren’t even aware that these tools exist, I figured I’d start there. So, without further ado, here’s my list of tools that every PHP programmer should know about.

Phing - a project build system

Phing LogoPhing is a project build system based on Apache ANT. The name is a recursive acronym, of sorts, that stands for PHing Is Not GNU make. Phing can do anything a traditional build system like GNU make can do, but without the steep learning curve.

The idea behind phing (and other build tools) is to evaluate a set of dependencies, then execute a set of PHP classes to properly install and configure an application. The build process is controlled by a simple XML configuration file. Out of the box, phing can perform token replacement (e.g., to change include paths on your development and production systems), execute SQL, move and copy files, run shell scripts, and more. You can also create your own custom tasks by extending the “task” class included with the package.

Phing is an invaluable tool for anyone who needs to deploy large scale PHP applications on more than a single server. But I’ve found it useful for simple scripts, too.

Xdebug - debugger and profiler tool

Xdebug LogoXdebug is a PHP extension that helps you debug and profile scripts. Among the most useful features of Xdebug are the new notice, warning, and error messages that are displayed after activation. If a script fails to execute properly, Xdebug will print a full stack trace in the error message, along with function names, parameter values, source files, and line numbers. A welcome feature for developers who are tired of the skimpy error reports from a default PHP install.

The extension has a number of more advanced features that allow developers to perform code coverage analysis, collect profiling information, and debug scripts interactively. The profiling functionality is particularly useful. The profiler uses a common output file format, allowing you to use tools like KCacheGrind to quickly find bottlenecks in your code. A good profiler is an essential tool for any serious developer, as it allows you to properly optimize your code while avoiding the hazards of premature optimization.

PHPUnit - unit testing framework

PHPUnit logoPHPUnit is a lightweight testing framework for PHP. It’s a complete port of JUnit 3.8.1 for PHP5, and is a member of the xUnit family of testing frameworks (which are based on a design by software patterns pioneer Kent Beck).

Unit tests form the foundation of several modern agile development methodologies, making PHPUnit a vital tool for many large scale PHP projects. The tool can also be used to generate code coverage reports using the Xdebug extension discussed earlier, and integrates with phing to automate testing.

Propel - object-relational mapping framework

Propel LogoPropel is an Object-Relational Mapping (ORM) framework for PHP5 that was originally based on the Apache Torque project. It provides a sophisticated, but easy to use database abstraction layer that allows you to work with database entities the same way you work with normal classes and objects in PHP. Propel allows you to define your database in a simple XML format which it uses to construct the database, and generate static classes for use in your application.

Propel is integrated into the popular Symfony PHP framework (among others), which has helped keep the code base flexible, modular, and portable. The project has excellent documentation, and a great support community.

phpMyAdmin / phpPgAdmin - web-based database administration

phpMyAdmin LogoAn oldy but a goody, phpMyAdmin is one of the most useful administrative tools available for any database (along with it’s PostgreSQL and SQLite cousins phpPgAdmin and phpSQLiteAdmin) . It’s useful for everything from constructing and altering databases to debugging applications and making backups. This is often the first thing I install after Apache, PHP and MySQL on a LAMP server. If you use MySQL, and somehow you haven’t heard of it, install it now.

Other Stuff

There are tons of excellent tools that fill all sorts of niches, and help provide a rich environment for PHP developers — I wish I could mention them all. A few more that I’ve found useful myself are PHP Beautifier, Spyc, Creole, and Smarty. I’m sure there are tons more that I either forgot, or have never heard of. So if you know of a great PHP development tool that I left out, please post a comment and let me (and everyone else) know about it!