Differences Between PHP 4 and 5 Some

Language Features

• PHP 5 allows limited type hinting. This allows you to specify that the parameter to a function or class method can only be of a specific class (or one of its subclasses), or an array. However, you may not specify any other scalar types.
• The foreach construct now supports by-reference declaration of the value element.
• A number of new functions, particularly for string and array manipulation, has also been added to the core platform.

Objects
• For all intents and purposes, all objects in PHP 5 are passed by reference. This means that assigning an object to a variable will not create a copy of the former, but simply creates another reference to it.
• Constants, as well as static methods and properties, can now be defined within the scope of a class.
• Class methods and properties now feature visibility, and can be declared as public, private or protected. Classes and methods can also be declared as final to prevent further inheritance.
• Since all objects are assigned by reference, you now need a specialized mechanism to copy objects. This is provided by the clone construct and the __clone() magic method.
• PHP 5 features unified constructors and destructors—all constructors should now be named __construct(), and the new __destruct() magic method has been added for object destruction.
• With the addition of interfaces and abstract classes, PHP developers now have far greater control over how they implement their object-oriented code. Interfaces can be used to define common APIs, while abstract classes provide models for class implementations that follow a specific blueprint.
• Class definitions can now be loaded on demand by using the __autoload() function.

MagicMethods
A multitude of new “magic” methods has been introduced in PHP 5:
• __get() and __set() are called when accessing or assigning an undefined object property, while __call() is executed when calling a non-existent method of a class.
• __isset() is called when passing an undefined property to the isset() construct.
• __unset() is called when passing an undefined property to unset().
• __toString() is called when trying to directly echo or print() an object.
• __set_state() is inserted dynamically by var_export() to allow for re-initialization on execution of var_export()’s output.

Selected New Extensions
• SimpleXML allows easy access to XML data using object and array notation.
• PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in the form of the libxml2-based DOM and XSL extensions.
• The PHP Data Objects (PDO) extension provides a unified database access extension that allows access to many different types of database systems by using a common interface. PDO is not an abstraction layer—except for prepared queries, it does nothing to abstract the actual database code (SQL), itself.
• The hash extension is a new replacement for the GPLed libmhash; it was added to the PHP core starting with version 5.1.2. It can produce hashes using many algorithms, including the  familiarMD5and SHA1, aswell as some more secure (albeit slower) algorithms, such as snefru.
• The Standard PHP Library (SPL) provides numerous interfaces that enhance the way classes interact with the PHP language, including the new Iterator interfaces.
• The new Reflection extension allows for runtime introspection of executing PHP code.

ErrorManagement
• Classes now support exceptions; the new set_exception_handler() function allows you to define a script-wide exception handler.
• The E_STRICT error reporting level has been added to the language to emit notices when legacy or deprecated code is encountered.


PHP Simple login Form - Part 1

In this blog we will learn to create a simple login form without using the database. We will be using harcoded username and password in authenticating file itself.

We will be creating two PHP file:
1. login.php
2. login_process.php


login.php

<html>

  <head>

    <title>Login Form</title>

  </head>



<body>

<form name="login" method="post" action="login_process.php">

    Username: <input type="text" name="username"/>

    Password: <input type="password" name="password"/>

    <input name="submit" type="submit" />

</form>

</body>

</html>



 login_process.php

<?php



// Following are the hardcoded username and   password for the login form. If user types anything else than below   value user wont be able to login.


$username = "myusername";

$password = "mypassword;




//Check if the input from the login.php are equal to our hardcoded variable


if($username == $_GET['username'] && $password =='$_GET['password']')

{

echo "Login success!";


} else {

echo "Login Failed!";


}





?>


Now browse the login.php in your broswer. Enter "myusername" as username and "mypassword" as password. Click on submit button will result with message "Login Success".

Else anything will display message "Login failed".


Thank you!

PHP Web Sercvices REST

REST
Representational State Transfer, or REST, is aWeb service architectural style in which the focus is on the presence of resources in the system. Each resourcemust be identified by a global identifier—a URI. To access these resources, clients communicate with the REST service by HTTP, and the server responds with a representation of the resource. This representation is often in the formof HTML or XML. Services that use the REST architecture are referred to as RESTful services; those who use or provide RESTful services are sometimes humorously referred to as RESTafarians.

There are a number of RESTful Web services, the most popular of which thrive in the blogosphere. In a loose sense,Web sites that provide RSS and RDF feeds provide a RESTful service. Loosening the definition even more reveals that the entire Web itself may be thought of as following a RESTful architecture with myriad resources and only a few actions to interact with them: GET, POST, PUT, HEAD, etc. In general, however, RESTfulWeb services allow standard GET requests to a resource and, in return, send an XML response. These services are not discoverable, so most providers
have well-documented APIs.

Since RESTfulWeb services are not discoverable, do not provide a WSDL, and have no common interface for communication, there is no one REST class provided in PHP to access all RESTful services; however, most RESTful services respond with XML data, and SimpleXML provides the best interface to interact with them. The popular bookmarking site, del.icio.us, is one example of aWeb site providing a REST service that returns XML data ready for SimpleXML to consume.
In the following example, the request made to api.del.icio.us requests all bookmarks tagged with the keyword foo:

$u = ’username’;
$p = ’password’;
$fooTag = "https://{$u}:{$p}@api.del.icio.us/v1/posts/all?tag=foo";
$bookmarks = new SimpleXMLElement($fooTag, NULL, true);
foreach ($bookmarks->post as $bookmark)
{
echo ’’;
echo htmlentities($bookmark[’description’]);
echo "

\n";
}


The URI stored in $fooTag is the resource identifier for the data retrieved. SimpleXML handles the request and conversion of the received XML data into an object. Note that del.icio.us uses HTTP authentication over SSL for its REST URIs; most RESTful services provide some kind of authentication or developer key scheme to gain access to the service.

The Standard PHP Library

The Standard PHP Library


The Standard PHP Library (SPL) is a great addition to PHP 5. It provides a number of very useful facilities that expose some of PHP’s internal functionality and allow the “userland” developer to write objects that are capable of behaving like arrays, or that transparently implement certain iterative design patterns to PHP’s own core functionality, so that you, for example, use a foreach() construct to loop through an object as if it were an array, or even access its individual elements using the array operator [].


SPL works primarily by providing a number of interfaces that can be used to implement the functionality required to perform certain operations. By far, the largest number of patterns exposed by SPL are iterators; they allow, among other things:

    Array Access to objects
    Simple Iteration
    Seekable Iteration
    Recursive Iteration
    Filtered Iteration


Accessing Objects as Arrays

The ArrayAccess interface can be used to provide a means for your object to expose themselves as pseudo-arrays to PHP:


interface ArrayAccess {

function offsetSet($offset, $value);

function offsetGet($offset);

function offsetUnset($offset);

function offsetExists($offset);

}


This interface provides the basic methods required by PHP to interact with an array:

    offsetSet() sets a value in the array
    offsetGet() retrieves a value from the array
    offsetUnset() removes a value from the array
    offsetExists() determines whether an element exists


As a very quick example, consider the following class, which “emulates” an array that only accepts elements with numeric keys:


class myArray implements ArrayAccess {

protected $array = array();

function offsetSet ($offset, $value) {

if (!is_numeric ($offset)) {

throw new Exception ("Invalid key $offset");

}

$this->array[$offset] = $value;

}

function offsetGet ($offset) {

return $this->array[$offset];

}

function offsetUnset ($offset) {

unset ($this->array[$offset]);

}

function offsetExists ($offset) {

return array_key_exists ($this->array, $offset);

}

}

$obj = new myArray();

$obj[1] = 2; // Works.

$obj[’a’] = 1; // Throws exception.


As you can see, this feature of SPL provides you with an enormous amount of control over one of PHP’s most powerful (and most useful) data types. Used properly, ArrayAccess is a great tool for building applications that encapsulate complex behaviours in a data type that everyone is used to.





Simple Iteration

The Iterator interface is the simplest of the iterator family, providing simple iteration over any single-dimension array. It looks like this:


interface Iterator {}

function current();

function next();

function rewind();

function key();

function valid();

function seek($key);

}


You can see a simple implementation of the interface that allows iteration over a private property containing a simple array:


class myData implements iterator {

private $_myData = array(

"foo",

"bar",

"baz",

"bat");

private $_current = 0;

function current() {

return $this->myData[$this->current];

}

function next() {

$this->current += 1;

}

function rewind() {

$this->current = 0;

}

function key() {

return $this->current;

}

function valid() {

return isset($this->myData[$this->current]);

}

}

$data = new myData();

foreach ($data as $key => $value) {

echo "$key: $value\n";

}


This example will iterate over each of the four elements in the myData private property in the exact same way foreach() works on a standard Array.



Seekable Iterators


The next step up from a standard Iterator is the SeekableIterator, which extends the standard Iterator interface and adds a seek() method to enable the ability to retrieve a specific item from internal data store. Its interface looks like this:


interface SeekableIterator {

function current();

function next();

function rewind();

function key();

function valid();

function seek($index);

}


Recursive Iteration


Recursive Iteration allows looping over multi-dimensional tree-like data structures.

SimpleXML, for example, uses recursive iteration to allow looping through complex XML document trees.


To understand how this works, consider the following complex array:


$company = array(

array("Acme Anvil Co."),

array(array("Human Resources",array("Tom","Dick","Harry")),

array("Accounting",array("Zoe","Duncan","Jack","Jane"))));


Our goal is to print out something like this:



Company: Acme Anvil Co.


Department: Human Resources


Tom

Dick

Harry


Department: Accounting


Zoe

Duncan

Jack

Jane



By extending RecursiveIteratorIterator, we can define the beginChildren() and endChildren() methods so that our class can output the start and end tags without any of the complexities normally associated with recursion (such as, for example, keeping track of multiple nested levels of nesting). The example shown below defines two classes, ou r custom RecursiveIteratorIterator and a very simple.


RecursiveArrayObject:


class Company_Iterator extends RecursiveIteratorIterator {

function beginChildren()

{

if ($this->getDepth() >= 3) {

echo str_repeat("\t", $this->getDepth() - 1);

echo "

    " . PHP_EOL;

}

}

function endChildren()

{

if ($this->getDepth() >= 3) {

echo str_repeat("\t", $this->getDepth() - 1);

echo "

" . PHP_EOL;

}

}

}


class RecursiveArrayObject extends ArrayObject {

function getIterator() {

return new RecursiveArrayIterator($this);

}

}


Then, to produce our desired end result, we simply use this code:


$it = new Company_Iterator(new RecursiveArrayObject($company));

$in_list = false;

foreach ($it as $item) {

echo str_repeat("\t", $it->getDepth());

switch ($it->getDepth()) {

case 1:

echo "
Company: $item

" . PHP_EOL;

break;

case 2:

echo "
Department: $item

" . PHP_EOL;

break;

default:

echo "

$item
" . PHP_EOL;

}

}



Filtering Iterators

The FilterIterator class can be used to filter the items returned by an iteration:


class NumberFilter extends FilterIterator {

const FILTER_EVEN = 1;

const FILTER_ODD = 2;

private $_type;

function__construct($iterator, $odd_or_even = self::FILTER_EVEN)

{

$this->_type = $odd_or_even;

parent::__construct($iterator);

}

function accept()

{

if ($this->_type == self::FILTER_EVEN) {

return ($this->current() % 2 == 0);

Elements of Object-oriented Design ” 169

} else {

return ($this->current() % 2 == 1);

}

}

}

$numbers = new ArrayObject(range(0, 10));

$numbers_it = new ArrayIterator($numbers);

$it = new NumberFilter($numbers_it, NumberFilter::FILTER_ODD);

foreach ($it as $number) {

echo $number . PHP_EOL;

}


The accept() method simply determines whether any given element should be allowed in the iteration; note that FilterIterator already implements al l of the methods of ArrayAccess, so that, effectively, from the outside our class can still be used as an array.

PHP - Registry Design pattern

The Registry Pattern

By taking the Singleton pattern a little further, we can implement the Registry pattern. This allows us to use any object as a Singleton without it being written specifically that way.

The Registry pattern can be useful, for example, if, for the bulk of your application, you use the same database connection, but need to connect to an alternate database to perform a small set of tasks every now and then. If your DB class is implemented as a Singleton, this is impossible (unless you implement two separate classes, that is)—but a Registry makes it very easy:


class Registry {

private static $_register;

public static function add(&$item, $name = null)

{

if (is_object($item) && is_null($name)) {

$name = get_class($item);

} elseif (is_null($name)) {

$msg = "You must provide a name for non-objects";

throw new Exception($msg);

}

$name = strtolower($name);

self::$_register[$name] = $item;

}

public static function &get($name)

{

$name = strtolower($name);

Elements of Object-oriented Design ” 161

if (array_key_exists($name, self::$_register)) {

return self::$_register[$name];

} else {

$msg = "’$name’ is not registered.";

throw new Exception($msg);

}

}

public static function exists($name)

{

$name = strtolower($name);

if (array_key_exists($name, self::$_register)) {

return true;

} else {

return false;

}

}

}

$db = new DB();

Registry::add($db);

// Later on

if (Registry::exists(’DB’)) {

$db = Registry::get(’DB’);

} else {

die(’We lost our Database connection somewhere. Bear with us.’);

}

PHP MVC - The Model-View-Controller Pattern

The Model-View-Controller Pattern

Unlike the patterns we have seen this far, Model-View-Controller (MVC) is actually quite complex. Its goal is that of providing a methodology for separating the business logic (model) from the display logic (view) and the decisional controls (controller). In a typical MVC setup, the user initiates an action (even a default one) by calling the Controller. This, in turn, interfaces with the Model, causing it to perform some sort of action and, therefore, changing its state. Finally, the View is called, thus causing the user interface to be refreshed to reflect the changes in the Model and the action requested of the Controller, and the cycle begins anew.

The clear advantage of the MVC pattern is its clear-cut approach to separating each domain of an application into a separate container. This, in turn, makes your applications easier to maintain and to extend, particularly because you can easily modularize each element, minimizing the possibility of code duplication.

PHP - Design pattern - The Factory Pattern

The Factory Pattern

The Factory pattern is used in scenarios where you have a generic class (the factory) that provides the facilities for creating instances of one or more separate “specialized” classes that handle the same task in different ways.

A good situation in which the Factory pattern provides an excellent solution is the management of multiple storage mechanisms for a given task. For example, consider configuration storage, which could be provided by data stores like INI files, databases or XML files interchangeably. The API that each of these classes provides is the same (ideally, implemented using an interface), but the underlying implementation changes. The Factory pattern provides us with an easy way to return a different data store class depending on either the user’s preference, or a set of environmental factors:


class Configuration {

const STORE_INI = 1;

const STORE_DB = 2;

const STORE_XML = 3;

public static function getStore($type = self::STORE_XML)

{

switch ($type) {

case self::STORE_INI:

return new Configuration_Ini();

case self::STORE_DB:

return new Configuration_DB();

case self::STORE_XML:

return new Configuration_XML();

default:

throw new Exception("Unknown Datastore Specified.");

}

}

}

class Configuration_Ini {

// ...

}

class Configuration_DB {

// ...

}

class Configuration_XML {

// ...

}

$config = Configuration::getStore(Configuration::STORE_XML);

PHP - Singleton Design Patern Theory

Design Pattern Theory:
Design patterns are nothing more than streamlined solutions to common problems. In fact, design patterns are not really about code at all—they simply provide guidelines that the developer, can translate into code for pretty much every possible language. 


The Singleton Pattern

The Singleton is, probably, the simplest design pattern. Its goal is to provide access to a single resource that is never duplicated, but that is made available to any portion of an application that requests it without the need to keep track of its existence. The most typical example of this pattern is a database connection, which normally only needs to be created once at the beginning of a script and then used throughout its code. Here’s an example implementation:


class DB {

private static $_singleton;

private $_connection;

private function__construct()

{

$this->_connection = mysql_connect();

}

public static function getInstance()

{

if (is_null (self::$_singleton)) {

self::$_singleton = new DB();

}

return self::$_singleton;

}

}

$db = DB::getInstance();



Our implementation of the DB class takes advantage of a few advanced OOP concepts that are available in PHP 5: we have made the constructor private, which effectively ensures that the class can only be instantiated from within itself. This is, in fact, done in the getInstance() method, which checks whether the static property $_connection has been initialized and, if it hasn’t, sets it to a new instance of DB. From this point on, getInstance() will never attempt to create a new instance of DB, and instead always return the initialized $_connection, thus ensuring that a database connection is not created more than once.