How to prepare ur Macbook for webdev

Install XAMPP:At first u have to download XAMPP for Mac OS X from this link and install as per their suggestion:http://www.apachefriends.org/en/xampp-macosx.html
installing XDebug on Mac OS X’s default PHP installation:
1. You are going to need to  download the source code from the XDebug website. (I suggest into your “Downloads” folder to make the rest of the process easier.
2. Unzip the archive from the finder.
3. Open up the Terminal, paste the following command in and hit enter: cd ~/Downloads/xdebug-2.0.3/xdebug-2.0.3/
4. Do the same for this command: phpize
5. This one too: MACOSX_DEPLOYMENT_TARGET=10.5 CFLAGS=”-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp” CCFLAGS=”-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe” CXXFLAGS=”-arch ppc -arch ppc64 -arch i386 -arch x86_64 -g -Os -pipe” LDFLAGS=”-arch ppc -arch ppc64 -arch i386 -arch x86_64 -bind_at_load” ./configure –enable-xdebug
6. And finally this one: make
7. We have just compiled the xdebug module. We now need to copy the compiled file binary file into a place where PHP can find it. From the terminal (again) run the following command: cp modules/xdebug.so /usr/lib/php/extensions/no-debug-non-zts-20060613/
8. Finally we need to edit the /etc/php.ini file so that PHP is aware of the new module. From the terminal run this command: open /etc/. This will open the /etc folder in the Finder allowing you to right-click on the php.ini file and open it in your preferred text-editor (TextEdit or TextMate for example).
9. At the very bottom of that file add the following:
zend_extension=/usr/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so
xdebug.file_link_format = “txmt://open?url=file://%f&line=%l”
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_autostart=1
10. In the terminal, for the last time (I promise), run the command: apachectl restart or simply restart your computer.

Now for installation test create a PHP script with a pile of errors in it and you should see colourful error messages when run in a browser (as apposed to plain old black and white text). Or you can download something like MacGDBp – a native debugging application for the Mac.

Display images in CakePHP

Today I face a problem as a beginner of CakePHP …How can I display image button with link in Cake. I wanted to use images as my buttons to edit and delete records and  navigate the admin pages.

1. Have to use HTML Helpers Image and Link, and we shall combine this 2. The CakePHP link helper is a handy tool to create links in your application. Here is the basic syntax:

<?php echo $html->link(’help!’,’/help’); ?>

And there’s a helper for creating images, too:

<?php echo $html->image(’add.gif’); ?>

Show HTML code of the image as the link:

<?php echo $html->link($html->image(’add.gif’),’/customers/add’)?>

2. For Image,
Syntax:

$html->image(string $path, array $htmlAttributes, boolean $return = false);

Example:

$html->image(’/img/images/cancel.png’, array(’class’ => ’save_button’));
3. For Link, the Syntax:

$html->link(string $title, string $url, array $htmlAttributes, string $confirmMessage = false, boolean $escapeTitle = true, boolean $return = false);

Example:

$html->link(’SAVE’, ‘/registers’, array(), false, false, false);

4. So to make an image clickable,

<?php echo $html->link($html->image(’/img/images/cancel.png’,array(’class’ => ’save_button’)), ‘/registers’, array(), false, false, false); ?>

And the best code is:
<?php echo $html->link($html->image(’add.gif’),’/customers/add’,array(’escape’=>false))?>

Hope it will help you to save time.

Top sites in CakePHP

CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code. Wanna learn CakePHP…..You have to find best sites on it. Given below are some of them:

1. CakeForge: CakeForge is a free service provided to Open Source developers offering easy access to the best in SVN, mailing lists, bug tracking, message boards/forums, task management, site hosting, permanent file archival, full backups, and total web-based administration.

2. CakePHP :It is most popular site for download, install and learn CakePHP.

3. Cakebaker:a rich site on Cake to bake. Learning a new framework should help me to grow as a developer.

4. CakePHP Bakery: Here u find resources, articles and much more… dont miss it.

5. Cakephp.nu:have some tutorials on Cake.

6. Cake for Beginners: article on style sheets.

7. 21 Things I Learned About CakePHP: Its really a nice one to learning.

8. The CakePHP Framework: A SitePoint Tutorial:

Can know the CakePHP’s Approach to the MVC Architecture

9. Cake.Insert Design Here: its features are:

10. Moving To CakePHP: another resource on Cakephp.

Lets enjoy the tour….

Using Style sheets in CakePHP

http://squio.nl/blog/wp-content/2008/02/cake12b.png

Recently I’m start working with CakePHP for one of my official project ‘The Bangabhaban website’. This is my second local project. First one was ‘votebd.com’ developed with CodeIgniter. I’m very happy to being developer of such a project. Lets happy starting.
I had to develop a template for demo purpose. here I discussed some CSS related problem solving tricks:
1. External Style Sheets: For access all images and style sheets you have to add following codes into .htaccess file.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ – [L]

2. AssetHelper: is a great  helper for
CSS and JS compression. You can find it in http://www.pseudocoder.com .

3. CSS Tidy: is an opensource CSS parser and optimiser. CSSTidy has full CSS2 support and a higher reliability. Any way to configure the helper and/or CSS Tidy to just combine all of
my CSS files into one:

$this->settings['remove_bslash'] = false;
$this->settings['compress_colors'] = false;
$this->settings['compress_font-weight'] = false;
$this->settings['lowercase_s'] = false;
$this->settings['optimise_shorthands'] = 0;
$this->settings['remove_last_;'] = false;
$this->settings['case_properties'] = 0;
$this->settings['sort_properties'] = false;
$this->settings['sort_selectors'] = false;
$this->settings['merge_selectors'] = 0;
$this->settings['discard_invalid_properties'] = false;
$this->settings['css_level'] = ‘CSS2.1′;
$this->settings['preserve_css'] = true;
$this->settings['timestamp'] = false;

The votebd.org website

votebd.org site

The votebd.org site

In the governance of a country, it is very important in this age to be informed about the people who will be running the country and representing it. Shushashoner Jannoy Nagorik’s Votebd.org does exactly this. Votebd.org tracks all the information related to contesting politicians and makes it available to people of Bangladesh. This is an effort in the direction of reducing corruption by making use of technology for transparency. In the past, even the voter list was not available to the common people. Shujan made the voter list available through this web site. Hopefully, an improvement in the political solution may eventually encourage an environment for honest, competent and devoted persons to join the politics.

Description:

Democracy is a government of the people, for the people, by the people. But do we have a medium to turn this theory into a practical reality. The website http://www.votebd.org has been developed for this purpose, to disseminate the personal information of the candidate who will contest in the local and national elections among the voters. Ironically, this effort is happening in Bangladesh. The information disseminated are educational qualification, criminal records (present and past), statements of assets and liabilities of candidates and dependents, profession, loan from bank and financial institutions, statement of income tax returns, source of election expenses, statement of actual election expenses etc. In addition, about 2,500 news published in the leading national dailies on corruption and criminalization made by politician, businessmen, government officials and others also posted in this site. It is being regularly updated.

Site link: http://www.votebd.org/

One of my projects Votebd.org won the Manthan Award 2008

Manthan Award 2008

Manthan Award 2008

Hi friends,

Hurrah! We have won the award. We deserved it. Its also a very good news for Bangladesh. One of my projects Votebd.org won the Manthan Award 2008 on E-Governance category. Bangladesh won five more awards- Roobon received more 2 awards on behalf of ankur and Unnayan TV. We had a big pavilion, hadn’t much logistics and not well furnished. Though we had a poor participation, we won 6 awards. It is really tremendous.

Roobon in the pavilion with Osama Manzar, the founder of Manthan

Roobon in the pavilion with Osama Manzar, the founder of Manthan

Address is:http://votebd.org/

Manthan Award 2008 News Links:

News in Gulf-Times
http://www.gulf-times.com/site/topics/article.asp?cu_no=2&item_no=249411&version=1&template_id=44&parent_id=24

The Daily Star of Bangladesh
http://www.thedailystar.net/pf_story.php?nid=59806

Prothom Alo
http://www.prothom-alo.com/index.news.details.php?nid=MTk1MzQ=

Unnayan News of Bangladesh
http://www.unnayannews.net/?p=783

Financial News of Bangladesh
http://www.thefinancialexpress-bd.info/search_index.php?page=detail_news&news_id=48626

Award committee have posted some photos and description.
http://manthanaward.org/index.asp
http://manthanaward.org/section_full_story.asp?id=652

Posted a news in Techtunes

http://techtunes.com.bd/news/tune-id/1561/

The Daily Ittefaq (IT page)- 24.10.2008
The Daily Sangbad (IT page)- 25.10.2008
The Daily Naya Diganta (IT Corner)- 25.10.2008
The Daily Amar Desh (IT corner)- 26.10.2008

For learn more please visit: www.manthanaward.org

Top open-source version control systems

Version control is an excellent way to allow unlimited number of people working on the same code base, without having to constantly send files back and forth. Designers and developers can both benefit from using such systems to keep copies of their files and designs. They can revert to earlier versions if something happens. Here I discuss some popular version control systems:

CVS is the Concurrent Versions System, the dominant open-source network-transparent version control system. It was first released in 1986. CVS is the de facto standard and is installed virtually everywhere. It’s useful for any designer or developer for backing up and sharing files. Tortoise CVS is a great client for CVS on Windows, and there are many different IDEs, such as Xcode (Mac), Eclipse, NetBeans and Emacs, that use CVS.

SVN or Subversion is the most popular version control system. Most open-source projects (SourceForge, Apache, Python, Ruby and many others) use it as a repository. Google Code uses Subversion exclusively to distribute code. For Windows, Tortoise SVN is a great file browser for viewing, editing and modifying your Subversion code base. For Mac, you have to use Versions. For Apple’s developer environment you have to use Xcode.

Bazaar have a very friendly user experience. It supports many different types of workflows, from solo to centralized to decentralized, with many variations in between. People have used it to version pretty much anything: single-file projects, your /etc directory and even the thousands of files and revisions in the source code for Launchpad, MySQL and Mailman. You can use it to fit almost any scenario of users and setups. It’s easy to modify and also embeddable, so you can add it to existing projects. Bazaar runs on GNU/Linux, UNIX, Windows and OS X out of the box. Bazaar is friendly, smart, fast, lightweight, extensible, embeddable, safe and free. Lists of plug-ins for Bazaar that are available under a free software license are given their plug-ins page. The page UsingPlugins gives detailed explanations about the plugin concept and installation instructions for plugins.

Git is a distributed version control systems initially developed by Linux kernel creator Linus Torvalds. Different branches hold different parts of the code instead one centralized code base to pull the code from. Git prides itself on being a fast and efficient system, and many major open-source projects use Git to power their repositories like Linux Kernel, Ruby on Rails, WINE, Fedora, X.org, Rubinius, and VLC etc. Git is used for version control of files, much like tools such as Mercurial, Subversion, CVS, Perforce, Bitkeeper, and Visual SourceSafe. GitHub has recently helped establish Git as a great version control system. It’s much harder to use for a beginner.

Mercurial is a cross-platform, distributed revision control tool for software developers. It was designed for larger projects, most likely outside the scope of designers and independent Web developers. It is extremely fast, and the creators built the software with performance as the most important feature. It’s easy to use because it’s functions are similar to those in other CVS systems. The creator and lead developer of Mercurial is Matt Mackall. Mercurial was initially written to run on Linux. It has been ported to Windows, Mac OS X, and most other Unix-like systems. Some projects using the Mercurial distributed RCS are Aldrin, Audacious, Dovecot IMAP server, Growl, MoinMoin wiki software, Mozilla, Netbeans, OpenJDK, SAGE and Sun’s OpenSolaris.

LibreSource is a versatile collaborative platform. It is used to manage collaborative projects. Open Source, modular and highly customizable, LibreSource is adapted to collaborative software development (forge), groupware, community leading, e-archiving and Web publishing. It has built-in features such as Wiki pages, forums, trackers, Synchronizers, Subversion repositories, files, download areas, drop boxes, forms, instant messaging and more. LibreSource is perfect for the developer or designer who doesn’t want to learn lots of technical jargon and wants to focus more on communication with the project’s members. LibreSource uses most of the advanced services provided by the ObjectWeb application server called JOnAS. Effective communication is a fundamental requirement for agile project management. LibreSource includes a Software Configuration Management tool called LibreSource Synchronizer which is innovative, simple and united. LibreSource simplifies the creation of a dynamic community and help to maintain and enhance team relationship in order to improve the cooperative efficiency. Just install the package and start collaborating.

Monotone is another distributed revision control system. Monotone is fairly easy to learn if you’re familiar with CVS systems, and it can import previous CVS projects.

Source Jammer is a source control and versioning system written in Java. It consists of a server-side component that maintains the files and version history, and handles check-in, check-out, etc. and other commands; and a client-side component that makes requests of the server and manages the files on the client-side file system. SourceJammer is coded in 100% Java, so it is platform independent.

GNU arch is a distributed revision control system that is part of the GNU Project and licensed under the GNU General Public License. It is used to keep track of the changes made to a source tree and to help programmers combine and otherwise manipulate changes made by multiple people or at different times. Being a distributed, decentralized versioning systems, each revision in GNU arch is uniquely globally identifiable; such identifier can be used in a distributed setting to easily merge or cherry-pick changes from completely disparate sources. Its other features are Atomic commits, Changeset oriented, easy branching, advanced margin, cryptographic signature, renaming and metadata tracking.

Version control Tools:

Design Pattern in PHP5- Abstract Factory

Abstract Factory:

A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software would create a concrete implementation of the abstract factory and then use the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) about which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from its general usage.

How to use it:

Class diagram of Amazon Online Book Shop:

In this example we have an abstract factory, AbstractBookFactory, that specifies two classes, AbstractPHPBook and AbstractMySQLBook, which will need to be created by the concrete factory.

The concrete class OReillyBookfactory extends AbstractBookFactory, and can create the OReillyMySQLBook and OReillyPHPBook classes, which are the correct classes for the context of OReilly. Thanks goes to FluffyCat.com as their article helps me a lot.

Examples Codes given below:

AbstractBookFactory.php

  abstract class AbstractBookFactory {

    abstract function makePHPBook();

    abstract function makeMySQLBook();

  }
download source, use right-click and “Save Target As…” to save with a .php extension.

OReillyBookFactory.php

  include_once('AbstractBookFactory.php');

  include_once('OReillyPHPBook.php');
  include_once('OReillyMySQLBook.php');

  class OReillyBookFactory extends AbstractBookFactory {

    private $context = "OReilly";  

    function makePHPBook() {return new OReillyPHPBook;}

    function makeMySQLBook() {return new OReillyMySQLBook;}

  }
download source, use right-click and “Save Target As…” to save with a .php extension.

SamsBookFactory.php

  include_once('AbstractBookFactory.php');

  include_once('SamsPHPBook.php');
  include_once('SamsMySQLBook.php');

  class SamsBookFactory extends AbstractBookFactory {

    private $context = "Sams";   

    function makePHPBook() {return new SamsPHPBook;}

    function makeMySQLBook() {return new SamsMySQLBook;}

  }
download source, use right-click and “Save Target As…” to save with a .php extension.

AbstractBook.php

    abstract class AbstractBook {

    abstract function getAuthor();

    abstract function getTitle();

    abstract function getPicture();
 }
download source, use right-click and “Save Target As…” to save with a .php extension.

AbstractMySQLBook.php

    include_once('AbstractBook.php');

    abstract class AbstractMySQLBook {

    private $subject = "MySQL";

  }
download source, use right-click and “Save Target As…” to save with a .php extension.

OReillyMySQLBook.php

  include_once('AbstractMySQLBook.php');

  class OReillyMySQLBook extends AbstractMySQLBook {

    private $author;

    private $title;

    private $picture;

 function __construct() {

      $this->author = 'George Reese, Randy Jay Yarger, and Tim King';
      $this->title  = 'Managing and Using MySQL';
      $this->picture = 'images/book3.jpg';
    }

    function getAuthor() {return $this->author;}

    function getTitle() {return $this->title;}

    function getPicture() {return $this->picture;}
  }
download source, use right-click and “Save Target As…” to save with a .php extension.

SamsMySQLBook.php

  include_once('AbstractMySQLBook.php');

  class SamsMySQLBook extends AbstractMySQLBook {

    private $author;

    private $title;

    private $picture;

 function __construct() {

      $this->author = 'Paul Dubois';
      $this->title  = 'MySQL, 3rd Edition';
      $this->picture = 'images/book6.jpg';
    }

    function getAuthor() {return $this->author;}

    function getTitle() {return $this->title;}

    function getPicture() {return $this->picture;}
 }
download source, use right-click and “Save Target As…” to save with a .php extension.

AbstractPHPBook.php

    include_once('AbstractBook.php');

    abstract class AbstractPHPBook {

    private $subject = "PHP";

  }
download source, use right-click and “Save Target As…” to save with a .php extension.

OReillyPHPBook.php

  include_once('AbstractPHPBook.php');

  class OReillyPHPBook extends AbstractPHPBook {

    private $author;

    private $title;

    private $picture;

    private static $oddOrEven = 'odd';

    function __construct() {

      //alternate between 2 books

      if ('odd' == self::$oddOrEven) {
        $this->author = 'Rasmus Lerdorf and Kevin Tatroe';
        $this->title  = 'Programming PHP';
        $this->picture = 'images/book2.jpg';
        self::$oddOrEven = 'even';
      } else {
        $this->author = 'David Sklar and Adam Trachtenberg';
        $this->title  = 'PHP Cookbook';
        $this->picture = 'images/book1.jpg';
        self::$oddOrEven = 'odd';
      }
    }

    function getAuthor() {return $this->author;}

    function getTitle() {return $this->title;}

    function getPicture() {return $this->picture;}
 }
download source, use right-click and “Save Target As…” to save with a .php extension.

SamsPHPBook.php

  include_once('AbstractPHPBook.php');

  class SamsPHPBook extends AbstractPHPBook {

    private $author;

    private $title;

    private $picture;

   function __construct() {

      //alternate randomly between 2 books

      mt_srand((double)microtime()*10000000);
      $rand_num = mt_rand(0,1);      

      if (1 > $rand_num) {
        $this->author = 'George Schlossnagle';
        $this->title  = 'Advanced PHP Programming';
        $this->picture = 'images/book4.jpg';
      } else {
        $this->author = 'Christian Wenz';
        $this->title  = 'PHP Phrasebook';
        $this->picture = 'images/book5.jpg';
      }
    }

    function getAuthor() {return $this->author;}

    function getTitle() {return $this->title;}

    function getPicture() {return $this->picture;}
 }
download source, use right-click and “Save Target As…” to save with a .php extension.

testAbstractFactory.php

  <?php

  include_once('OReillyBookFactory.php');
  include_once('SamsBookFactory.php');

  echo tagins("html");
  echo tagins("head");
  echo tagins("/head");
  echo tagins("body");
//
echo '<img src="images/header.gif" width="100%">';
//
  echo "<h3>Amazon Online Book Shop</h3>";
  echo tagins("br");

  echo 'All OReillyBooks'.tagins("br");
  $bookFactoryInstance = new OReillyBookFactory;
  testConcreteFactory($bookFactoryInstance);

  echo tagins("br");

  echo 'All SamsBooks Factory'.tagins("br");
  $bookFactoryInstance = new SamsBookFactory;
  testConcreteFactory($bookFactoryInstance);  

  echo tagins("br");
  echo "";
  echo tagins("br");
  //
	echo '<img src="images/footer-toptile.gif">';
//
  echo tagins("/body");
  echo tagins("/html");

  function testConcreteFactory($bookFactoryInstance) {
    $phpBookOne = $bookFactoryInstance->makePHPBook();
    echo '<img src="'.$phpBookOne->getPicture().'">'.tagins("br");
    echo 'Author: '.
	  $phpBookOne->getAuthor().tagins("br");
    echo 'Title: '.
	  $phpBookOne->getTitle().tagins("br");
//
	echo '<p class="MsoNormal" style="text-align: center;
line-height: 12pt; margin-top: 2px; 

margin-bottom: 2px;"><span style="font-family: Verdana;
 font-size: xx-small;"> <a 

href="http://www.edutechindia.org/currency.asp?id=1&amp;catid=
1&amp;p=m"> Add to Cart 

</a></span></p>';
//
    $phpBookTwo = $bookFactoryInstance->makePHPBook();
    echo '<img src="'.$phpBookTwo->getPicture().'">'.tagins("br");
    echo 'Author: '.
	  $phpBookTwo->getAuthor().tagins("br");
    echo 'Title: '.
	  $phpBookTwo->getTitle().tagins("br");
    //
	echo '<p class="MsoNormal" style="text-align: center;
line-height: 12pt; margin-top: 2px; 

margin-bottom: 2px;"><span style="font-family: Verdana;
font-size: xx-small;"> <a 

href="http://www.edutechindia.org/currency.asp?id=1&amp;catid=
1&amp;p=m"> Add to Cart 

</a></span></p>';
//
	$mySqlBook = $bookFactoryInstance->makeMySQLBook();
   echo '<img src="'.$mySqlBook->getPicture().'">'.tagins("br");
    echo 'MySQL Author: '.
	  $mySqlBook->getAuthor().tagins("br");
    echo 'MySQL Title: '.
	  $mySqlBook->getTitle().tagins("br");
//
	echo '<p class="MsoNormal" style="text-align: center;
line-height: 12pt; margin-top: 2px; 

margin-bottom: 2px;"><span style="font-family: Verdana; font-size:
 xx-small;"> <a 

href="http://www.edutechindia.org/currency.asp?id=1&amp;catid=
1&amp;p=m"> Add to Cart 

</a></span></p>';
//
  }

  //doing this so code can be displayed without breaks
  function tagins($stuffing) {
    return "<".$stuffing.">";
  }

?>
download source, use right-click and “Save Target As…” to save with a .php extension.

output of testAbstractFactory.php

DESIGN PATTERNS in PHP

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. The advantage of knowing and using these patterns is save time as well as give developers a common language in software design. Here I discuss the implementation of some common design patterns that are easily adapted to PHP.

1. Strategy Pattern:

The strategy pattern is typically used when your programmer’s algorithm
should be interchangeable with different variations of the algorithm. For
example, if you have code that creates an image, under certain circumstances, you might want to create JPEGs and under other circumstances, you might want to create GIF files.
The strategy pattern is usually implemented by declaring an abstract
base class with an algorithm method, which is then implemented by inheriting concrete classes. At some point in the code, it is decided what concrete strategy is relevant; it would then be instantiated and used wherever relevant.
Our example shows how a download server can use a different file selection
strategy according to the web client accessing it. When creating the
HTML with the download links, it will create download links to either .tar.gz
files or .zip files according to the browser’s OS identification. Of course, this
means that files need to be available in both formats on the server. For simplicity’s sake, assume that if the word “Win” exists in $_SERVER["HTTP_
USER_AGENT"], we are dealing with a Windows system and want to create .zip
links; otherwise, we are dealing with systems that prefer .tar.gz.
In this example, we would have two strategies: the .tar.gz strategy and
the .zip strategy, which is reflected as the following strategy hierarchy (see
Figure 1).


Figure 1: Strategy hierarchy.

The following code snippet should give you an idea of how to use such a
strategy pattern:
abstract class FileNamingStrategy {
abstract function createLinkName($filename);
}
class ZipFileNamingStrategy extends FileNamingStrategy {
function createLinkName($filename)
{
return “http://downloads.foo.bar/$filename.zip&#8221;;
}
}
class TarGzFileNamingStrategy extends FileNamingStrategy {
function createLinkName($filename)
{
return “http://downloads.foo.bar/$filename.tar.gz&#8221;;
}
}
if (strstr($_SERVER["HTTP_USER_AGENT"], “Win”)) {
$fileNamingObj = new ZipFileNamingStrategy();
} else {
$fileNamingObj = new TarGzFileNamingStrategy();
}
$calc_filename = $fileNamingObj->createLinkName(“Calc101″);
$stat_filename = $fileNamingObj->createLinkName(“Stat2000″);
print <<<EOF
<h1>The following is a list of great downloads<</h1>
<br>
<a href=”$calc_filename”>A great calculator</a><br>
<a href=”$stat_filename”>The best statistics application</a><br>
<br>
EOF;
Accessing this script from a Windows system gives you the following
HTML output:
<h1>The following is a list of great downloads<</h1>
<br>
<a href=”http://downloads.foo.bar/Calc101.zip”>A great calculator<
/a><br>
<a href=”http://downloads.foo.bar/Stat2000.zip”>The best statistics
application</a><br>
<br>

Tip: The strategy pattern is often used with the factory pattern, which is
described later in this section. The factory pattern selects the correct strategy.

2. Singleton Pattern:
The singleton pattern is probably one of the best-known design patterns.
You have probably encountered many situations where you have an object that
handles some centralized operation in your application, such as a logger
object. In such cases, it is usually preferred for only one such application-wide
instance to exist and for all application code to have the ability to access it.
Specifically, in a logger object, you would want every place in the application
that wants to print something to the log to have access to it, and let the centralized
logging mechanism handle the filtering of log messages according to
log level settings. For this kind of situation, the singleton pattern exists.
Making your class a singleton class is usually done by implementing a
static class method getInstance(), which returns the only single instance of
the class. The first time you call this method, it creates an instance, saves it in
a private static variable, and returns you the instance. The subsequent
times, it just returns you a handle to the already created instance.
Here’s an example:
class Logger {
static function getInstance()
{
if (self::$instance == NULL) {
self::$instance = new Logger();
}
return self::$instance;
}
private function __construct()
{
}
private function __clone()
{
}
function Log($str)
{
// Take care of logging
}
static private $instance = NULL;
}
Logger::getInstance()->Log(“Checkpoint”);

The essence of this pattern is Logger::getInstance(), which gives you
access to the logging object from anywhere in your application, whether it is
from a function, a method, or the global scope.
In this example, the constructor and clone methods are defined as private.
This is done so that a developer can’t mistakenly create a second
instance of the Logger class using the new or clone operators; therefore, getInstance() is the only way to access the singleton class instance.

3. Factory Pattern:

Polymorphism and the use of base class is really the center of OOP. However,
at some stage, a concrete instance of the base class’s subclasses must be created.
This is usually done using the factory pattern. A Factory class has a
static method that receives some input and, according to that input, it decides
what class instance to create (usually a subclass).
Say that on your web site, different kinds of users can log in. Some are
guests, some are regular customers, and others are administrators. In a common
scenario, you would have a base class User and have three subclasses:
GuestUser, CustomerUser, and AdminUser. Likely User and its subclasses would
contain methods to retrieve information about the user (for example, permissions
on what they can access on the web site and their personal preferences).
The best way for you to write your web application is to use the base class
User as much as possible, so that the code would be generic and that it would
be easy to add additional kinds of users when the need arises.
The following example shows a possible implementation for the four User
classes, and the UserFactory class that is used to create the correct user object
according to the username:
abstract class User {
function __construct($name)
{
$this->name = $name;
}
function getName()
{
return $this->name;
}
// Permission methods
function hasReadPermission()
{
return true;
}
function hasModifyPermission()
{
return false;

}
function hasDeletePermission()
{
return false;
}
// Customization methods
function wantsFlashInterface()
{
return true;
}
protected $name = NULL;
}
class GuestUser extends User {
}
class CustomerUser extends User {
function hasModifyPermission()
{
return true;
}
}
class AdminUser extends User {
function hasModifyPermission()
{
return true;
}
function hasDeletePermission()
{
return true;
}
function wantsFlashInterface()
{
return false;
}
}
class UserFactory {
private static $users = array(“Andi”=>”admin”, “Stig”=>”guest”,
“Derick”=>”customer”);
static function Create($name)
{
if (!isset(self::$users[$name])) {
// Error out because the user doesn’t exist
}
switch (self::$users[$name]) {

case “guest”: return new GuestUser($name);
case “customer”: return new CustomerUser($name);
case “admin”: return new AdminUser($name);
default: // Error out because the user kind doesn’t exist
}
}
}
function boolToStr($b)
{
if ($b == true) {
return “Yes\n”;
} else {
return “No\n”;
}
}
function displayPermissions(User $obj)
{
print $obj->getName() . “‘s permissions:\n”;
print “Read: ” . boolToStr($obj->hasReadPermission());
print “Modify: ” . boolToStr($obj->hasModifyPermission());
print “Delete: ” . boolToStr($obj->hasDeletePermission());
}
function displayRequirements(User $obj)
{
if ($obj->wantsFlashInterface()) {
print $obj->getName() . ” requires Flash\n”;
}
}
$logins = array(“Andi”, “Stig”, “Derick”);
foreach($logins as $login) {
displayPermissions(UserFactory::Create($login));
displayRequirements(UserFactory::Create($login));
}
Running this code outputs
Andi’s permissions:
Read: Yes
Modify: Yes
Delete: Yes
Stig’s permissions:
Read: Yes
Modify: No
Delete: No
Stig requires Flash
Derick’s permissions:
Read: Yes
Modify: Yes
Delete: No
Derick requires Flash
This code snippet is a classic example of a factory pattern. You have a class
hierarchy (in this case, the User hierarchy), which your code such as displayPermissions() treats identically. The only place where treatment of the classes differ is in the factory itself, which constructs these instances. In this example, the factory checks what kind of user the username belongs to and creates its class accordingly. In real life, instead of saving the user to user-kind mapping in a static array, you would probably save it in a database or a configuration file.

Tip: Besides Create(), you will often find other names used for the factory
method, such as factory(), factoryMethod(), or createInstance().

4. Observer Pattern:

PHP applications, usually manipulate data. In many cases, changes to one
piece of data can affect many different parts of your application’s code. For
example, the price of each product item displayed on an e-commerce site in the
customer’s local currency is affected by the current exchange rate. Now,
assume that each product item is represented by a PHP object that most likely
originates from a database; the exchange rate itself is most probably being
taken from a different source and is not part of the item’s database entry. Let’s
also assume that each such object has a display() method that outputs the
HTML relevant to this product.
The observer pattern allows for objects to register on certain events
and/or data, and when such an event or change in data occurs, it is automatically
notified. In this way, you could develop the product item to be an observer
on the currency exchange rate, and before printing out the list of items, you
could trigger an event that updates all the registered objects with the correct
rate. Doing so gives the objects a chance to update themselves and take the
new data into account in their display() method.
Usually, the observer pattern is implemented using an interface called
Observer, which the class that is interested in acting as an observer must
implement.
For example:

interface Observer {
function notify($obj);
}
An object that wants to be “observable” usually has a register method
that allows the Observer object to register itself. For example, the following
might be our exchange rate class:

class ExchangeRate {
static private $instance = NULL;
private $observers = array();
private $exchange_rate;
private function ExchangeRate() {
}
static public function getInstance() {
if (self::$instance == NULL) {
self::$instance = new ExchangeRate();
}
return self::$instance;
}
public function getExchangeRate() {
return $this->$exchange_rate;
}
public function setExchangeRate($new_rate) {
$this->$exchange_rate = $new_rate;
$this->notifyObservers();
}
public function registerObserver($obj) {
$this->observers[] = $obj;
}
function notifyObservers() {
foreach($this->observers as $obj) {
$obj->notify($this);
}
}
}
class ProductItem implements Observer {
public function __construct() {
ExchangeRate::getInstance()->registerObserver($this);
}
public function notify($obj) {
if ($obj instanceof ExchangeRate) {
// Update exchange rate data
print “Received update!\n”;
}
}
}
$product1 = new ProductItem();
$product2 = new ProductItem();
ExchangeRate::getInstance()->setExchangeRate(4.5);
This code prints
Received update!
Received update!

Although the example isn’t complete (the ProductItem class doesn’t do
anything useful), when the last line executes (the setExchangeRate() method), both $product1 and $product2 are notified via their notify() methods with the new exchange rate value, allowing them to recalculate their cost.
This pattern can be used in many cases; specifically in web development,
it can be used to create an infrastructure of objects representing data that
might be affected by cookies, GET, POST, and other input variables.

Thanks to the advances of PHP 5, using common OO methodologies, such as
design patterns, has now become more of a reality than with past PHP versions. For more you can visit http://www.cetus-links.org/.

How you make an OOP Website in PHP

Object-oriented programming (OOP) is a programming paradigm that uses “objects” and their interactions to design applications and computer programs. Programming techniques may include features such as encapsulation, modularity, polymorphism, and inheritance. It was not commonly used in mainstream software application development until the early 1990s. Many modern programming languages now support OOP.

Fundamental Concepts of OOP which takes from Wikipedia:

Class
Defines the abstract characteristics of a thing (object), including the thing’s characteristics (its attributes, fields or properties) and the thing’s behaviors (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context. Also, the code for a class should be relatively self-contained (generally using encapsulation). Collectively, the properties and methods defined by a class are called members.
Object
A pattern (exemplar) of a class. The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur.
Instance
One can have an instance of a class or a particular object. The instance is the actual object created at runtime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of the attributes of a particular object is called its state. The object consists of state and the behaviour that’s defined in the object’s class.
Method
An object’s abilities. In language, methods are verbs. Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie‘s methods. She may have other methods as well, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usually affects only one particular object; all Dogs can bark, but you need only one particular dog to do the barking.
Message passing
“The process by which an object sends data to another object or asks the other object to invoke a method.” [2] Also known to some programming languages as interfacing. E.g. the object called Breeder may tell the Lassie object to sit by passing a ‘sit’ message which invokes Lassie’s ‘sit’ method. The syntax varies between languages, for example: [Lassie sit] in Objective-C. In Java code-level message passing corresponds to “method calling”. Some dynamic languages use double-dispatch or multi-dispatch to find and pass messages.
Inheritance
‘Subclasses’ are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.
For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In this case, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method called bark() and a property called furColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever) will inherit these members, meaning that the programmer only needs to write the code for them once.
Each subclass can alter its inherited traits. For example, the Collie class might specify that the default furColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() method produces a high pitch by default. Subclasses can also add new members. The Chihuahua subclass could add a method called tremble(). So an individual chihuahua instance would use a high-pitched bark() from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chihuahua object would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an ‘is-a’ relationship: Lassie is a Collie. A Collie is a Dog. Thus, Lassie inherits the methods of both Collies and Dogs.
Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors being an ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimera object could be created from these two which inherits all the (multiple) behavior of cats and dogs. This is not always supported, as it can be hard both to implement and to use well.
Abstraction
Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.
For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy’s pets.
Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.
Encapsulation
Encapsulation conceals the functional details of a class from objects that send messages to it.
For example, the Dog class has a bark() method. The code for the bark() method defines exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie‘s friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface — those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. For example, an interface can ensure that puppies can only be added to an object of the class Dog by code in that class. Members are often specified as public, protected or private, determining whether they are available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow one to specify which classes may access any member.
Polymorphism
Polymorphism allows the programmer to treat derived class members just like their parent class’ members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as ‘+’, to perform several different functions depending on the implementation. The ‘+’ operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the concatenation operator, ‘+’, to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism. Many OOP languages also support Parametric Polymorphism, where code is written without mention of any specific type and thus can be used transparently with any number of new types. Pointers are an example of a simple polymorphic routine that can be used with many different types of objects.[3]
Decoupling
Decoupling allows for the separation of object interactions from classes and inheritance into distinct layers of abstraction. A common use of decoupling is to polymorphically decouple the encapsulation, which is the practice of using reusable code to prevent discrete code modules from interacting with each other.

Not all of the above concepts are to be found in all object-oriented programming languages, and so object-oriented programming that uses classes is called sometimes class-based programming. In particular, prototype-based programming does not typically use classes. As a result, a significantly different yet analogous terminology is used to define the concepts of object and instance, although there are no objects in these languages.

PHP5 also support OOP now. Here we find how we could make a website using OOP technique. The first thing we’re going to look at is make your site object-oriented in a very simple way – we’ll make a site class and a page class. Then we’ll move onto looking at how we could subclass the page class so that we can have different types of page rendering differently.

index.php code:

<?php
include 'config.php';

$site = new csite();

// this is a function specific to this site!
initialise_site($site);

$page = new cpage("Magnolia Shoping cart");
$site->setPage($page);

$content = <<<EOT
Welcome to my Magnolia Shoping Cart!
EOT;
$page->setContent($content);

$site->render();
?>

The config.php file will contain the site-specific information – all the information that shouldn’t be inside our classes and shouldn’t be repeated in every page. We set $site to be an instance of our site, and then call a function called initialise_site() to set it up with our basic, site-specific settings – that function will be in config.php.
Next we create a cpage object, passing into the constructor the title of the page, then use the setPage() function of our csite class to add the page to our site for rendering.
config.php code:
<?php
function __autoload($class) {
include
"$class.php";
}

function

initialise_site(csite $site) {
$site->addHeader("header.php");
$site->addFooter("footer.php");
}
?>

The __autoload() function will load the pages dynamically and in initialise_site() function we add site-specific header and footer files for this site. ote that the __autoload() function will look for csite.php and cpage.php, so we need to supply those two.
csite.php code:
<?php
class csite {
private
$headers;
private
$footers;
private
$page;

public function

__construct() {
$this->headers = array();
$this->footers = array();
}

public function

__destruct() {
// clean up here
}

public function

render() {
foreach(
$this->headers as $header) {
include
$header;
}

$this->page->render();

foreach(

$this->footers as $footer) {
include
$footer;
}
}

public function

addHeader($file) {
$this->headers[] = $file;
}

public function

addFooter($file) {
$this->footers[] = $file;
}

public function

setPage(cpage $page) {
$this->page = $page;
}
}
?>

The cpage.php code:
<?php
class cpage {
private
$title;
private
$content;

public function

__construct($title) {
$this->title = $title;
}

public function

__destruct() {
// clean up here
}

public function

render() {
echo
"<H1>{$this->title}</H1>";

include("body.php");
echo
$this->content;
}

public function

setContent($content) {
$this->content = $content;
}
}
?>

So we’ve got $title and $content variables there.
The header.php file is site-specific, and so could be anything you want. Here’s an example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>My Website</TITLE>
</HEAD>

<BODY>

<table width="100%" border="0" cellspacing="0" align="center" height="28">
<tr>
<td><img src="images/header.gif" width="100%"></td>
</tr>
</table>
<table width="100%" border="0" cellspacing="0" align="center" height="28">
<tr>
<td align="center"><h2>Magnolia Shoping cart</h2></td>
</tr>
</table>

Here’s a body.php example also:
<table id=”AutoNumber1″ style=”border-collapse: collapse;” border=”0″ cellspacing=”0″ cellpadding=”0″ width=”100%” bordercolor=”#111111″>
<tbody>
<tr>
<td colspan=”3″></td>
</tr>
<tr>
<td width=”23%”><img src=”images/jol3-5.gif” border=”0″ alt=”" width=”86″ height=”100″ /></td>
<td width=”2%” valign=”top”>
<p style=”margin-top: 2px; margin-bottom: 2px;”><strong> </strong></p>
</td>
<td valign=”top”>
<p style=”margin-top: 2px; margin-bottom: 2px;”><strong><span style=”font-family: Verdana; color: #cc3300; font-size: x-small;”>Joy of Learning-I</span></strong></p>

<p style=”text-align: justify; line-height: 12pt; margin-top: 2px; margin-bottom: 2px;”><span style=”letter-spacing: -0.15pt;”><span style=”font-size: x-small;”> <span style=”font-family: Verdana;”>A handbook of 75 activities to help children understand different facets of the environment, developed for the National Council for Educational Research and Training (NCERT). Each activity is presented in a user-friendly format with suggestions as to the subjects in which the activity can be introduced; variations/extensions; ideas for evaluation, etc. Useful for teachers of standards 3 to 5. Pages 88
</span></span></span>
<p class=”MsoNormal” style=”text-align: center; line-height: 12pt; margin-top: 2px; margin-bottom: 2px;”><span style=”font-family: Verdana; font-size: xx-small;”> <a href=”http://www.edutechindia.org/currency.asp?id=1&amp;catid=1&amp;p=m”&gt; Add to Cart </a></span></p>
</td>
</tr>
<tr>
<td colspan=”3″><hr size=”1″ noshade=”noshade” /></td>
</tr>
<tr>
<td width=”23%”><img src=”images/nsins.gif” border=”0″ alt=”" width=”86″ height=”100″ /></td>
<td width=”2%” valign=”top”>
<p style=”margin-top: 2px; margin-bottom: 2px;”><strong> </strong></p>
</td>
<td valign=”top”>
<p style=”margin-top: 2px; margin-bottom: 2px;”><strong><span style=”font-family: Verdana; color: #cc3300; font-size: x-small;”>Nature Scope -Incredible Insects</span></strong></p>

<p style=”text-align: justify; line-height: 12pt; margin-top: 2px; margin-bottom: 2px;”><span style=”letter-spacing: -0.15pt;”><span style=”font-size: x-small;”> <span style=”font-family: Verdana;”>NatureScope India is a creative education series dedicated to inspiring children towards an understanding and appreciation of the natural world while developing the skills they will need to make responsible decisions about the environment. Divided into different sections, each section deals with an insect theme and includes background information and activities related to that theme.In English Pages: 51
</span></span></span>
<p class=”MsoNormal” style=”text-align: center; line-height: 12pt; margin-top: 2px; margin-bottom: 2px;”><span style=”font-family: Verdana; font-size: xx-small;”> <a href=”http://www.edutechindia.org/currency.asp?id=148&amp;catid=1&amp;p=m”&gt; Add to Cart </a></span></p>
</td>
</tr>
<tr>
<td colspan=”3″><hr size=”1″ noshade=”noshade” /></td>
</tr>
<tr>
<td width=”23%”><img src=”images/clothfold.gif” border=”0″ alt=”" width=”86″ height=”100″ /></td>
<td width=”2%” valign=”top”>
<p style=”margin-top: 2px; margin-bottom: 2px;”><strong> </strong></p>
</td>
<td valign=”top”>
<p style=”margin-top: 2px; margin-bottom: 2px;”><strong><span style=”font-family: Verdana; color: #cc3300; font-size: x-small;”>Handmade Seminar Folder with Cloth Covering</span></strong></p>

<p style=”text-align: justify; line-height: 12pt; margin-top: 2px; margin-bottom: 2px;”><span style=”letter-spacing: -0.15pt;”><span style=”font-size: x-small;”> <span style=”font-family: Verdana;”>Available in different colours, designs and patterns. Price Rs. 50.00 onwards.
</span></span></span>
<p class=”MsoNormal” style=”text-align: center; line-height: 12pt; margin-top: 2px; margin-bottom: 2px;”><span style=”font-family: Verdana; font-size: xx-small;”> <a href=”http://www.edutechindia.org/currency.asp?id=158&amp;catid=21&amp;p=m”&gt; Add to Cart </a></span></p>
</td>
</tr>
<tr>
<td colspan=”3″><hr size=”1″ noshade=”noshade” /></td>
</tr>
<tr>
<td width=”23%”><img src=”images/sclabelbirds.gif” border=”0″ alt=”" width=”86″ height=”100″ /></td>
<td width=”2%” valign=”top”>
<p style=”margin-top: 2px; margin-bottom: 2px;”><strong> </strong></p>
</td>
<td valign=”top”>
<p style=”margin-top: 2px; margin-bottom: 2px;”><strong><span style=”font-family: Verdana; color: #cc3300; font-size: x-small;”>School Labels – Birds</span></strong></p>

<p style=”text-align: justify; line-height: 12pt; margin-top: 2px; margin-bottom: 2px;”><span style=”letter-spacing: -0.15pt;”><span style=”font-size: x-small;”> <span style=”font-family: Verdana;”>Sheet of 36 labels
</span></span></span>
<p class=”MsoNormal” style=”text-align: center; line-height: 12pt; margin-top: 2px; margin-bottom: 2px;”><span style=”font-family: Verdana; font-size: xx-small;”> <a href=”http://www.edutechindia.org/currency.asp?id=160&amp;catid=21&amp;p=m”&gt; Add to Cart </a></span></p>
</td>
</tr>
</tbody></table>

Here’s a footer.php example also:
<table width=”100%” border=”0″ cellspacing=”0″ align=”center” height=”28″>
<tr>
<td><img src=”images/footer-toptile.gif”></td>
</tr>
</table>
</BODY>
</HTML>
Now all works complete. Run it to see a very simple site.
Your website is totally developed in OOP way. What a great feelings.
Follow

Get every new post delivered to your Inbox.