Monday, November 12, 2007

Planning PHP Projects

Planning PHP Projects

The biggest problem I see is most PHP scripts is a lack of structure and organization. What heralds this is a lack of planning. Many PHP programmers don't think through projects before they dive into the coding. This is a tutorial I wrote 3-4 months ago. I have learned a lot since then, especially concerning OOP techniques. I am currently working on a new version, however, I considered it complete enough to be posted here. Please comment so that the next revision of it will improve!

Planning?

When coding a large, or even moderate or small size, project the most important thing is planning. When you get to the level in which you will, without a tutorial or book, be programming something on your own you know you can do the coding. You know you can connect to databases, print things to the screen, create basic classes, etc. However, what many people do when they reach this stage is skip the planning process and dive right into the coding procedure.
While improvisation during programming is good, if you want a streamlined application that shows consisten programming practices, is easy to update, and is simple to code, the best tool is a plan. If you have a database structure, if you have outlined the structure of your code, if you know exactly what you want your application to do, programming is a breeze. Succesful planning is not treated in most books or tutorials, because in the books and tutorials the author does the planning for you. But once you are creating an application on your own, you must plan and look ahead.
Hopefully, this tutorial will help you understand how to plan an application. It will be, eventually, a two or three part series that will address planning features, planning classes, database structure, templating, message abstraction, and hopefully some basic coding technique. It is not intended to teach you how to code PHP, instead it is intended to show you how to structure and plan your code well.
Enjoy! I have utilized these practices while creating programs, and when it comes to adding features and creating new versions, planning and good code structure is the most important part of the process.

Planning the Program Features

The basic need is to understand what your program will be doing. The example I will use throughout is a basic guestbook application. Initially, what you want to do is figure out the basic features that will contain everything else. For a guestbook application, I would probably outline something like this:
1.) The ability to view entries 2.) The ability to post entries 3.) Administration 4.) Templating
How did I arrive at these features? I looked at other guestbooks and saw what they had and tried to categorize it. I then looked to see what they didn't have that I would like and added that in and categorized it. The whole idea is just to have the roughest outline of the most basic features.
Now we can try to flesh it out. Brainstorm what you think a guestbook (or whatever your application is) should have. I figured out something like this:

  1. Viewing entries
    1. Default view is 10 entries at a time, but allow people to view more
    2. Maybe JavaScript expanding and collapsing of entries?
    3. Transfer BBCode to HTML
  2. Posting entries
    1. Place a link on every page to the posting page
    2. Required fields: name, entry
    3. Optional fields: e-mail, website, IM usernames, location
    4. Hidden fields: IP address (for banning spammers)
  3. Administration
    1. Editing posts.
    2. Deleting posts.
    3. Banning people by IP (if someone consistently spams your guestbook)
    4. Bad word filter settings?
    5. Basic settings -- site name, guestbook name, site URL, database user/pass/database/host
    6. Admin response to entries
    7. Easy modification of templates and addition of new ones through the Admin panel
    8. Login and authentication, obviously
  4. Templating
    1. Basic replacing of {VARS} with values from DB or flatfile
    2. If you don't want to code it yourself, systems such as Smarty and patTemplate are excellent and easy to use

This is by no means complete, but can you see that once a list such as this is available, programming is made that much easier? When I begin to write the script, I can see exactly where I want to go. I know how the various features will connect, and I understand the purpose behind what I am doing.

Planning the Coding

Here is where you decide how the backend/coding will work. Do you want to run it off a database? If so, which one (MySQL, SQLite, PostGreSQL, MS Access, etc.). Or do you want to do it flatfile, if so, how? And in general, what will the structure of your code be? My advice for large applications can be summed up in three words: Object Oriented Programming.
The best way to program a large PHP program -- and indeed any large program (and in fact many small ones) -- is to use OOP. Think of it this way. Say you have a forum script and it is OOP. You have a class named view. Inside that, you have a function called viewThreads(); that accepts a few different values to tell it which threads to view. Now, suppose you have a page titled viewforum.php and at one point you want to view certain threads. So you call $view->viewThreads(); . You also have a search function, and in it you want to view certain threads. Well, you call the same function. Now say you want to change the programming for viewing threads. If you didn't have OOP, you'd have to open up every file that views threads and change it. With OOP, you just change the class. You could just do a bunch of functions, but the use of OOP is that a class is more organized, can do something automatically every time it is called, and can be easily extended. (Not to mention more advanced class passing and handling functions not introduced until PHP 5)
So, you've decided to use classes. Or rather, I've decided that you will at least for this tutorial. What classes will you have, and what will each do? If you are going to use a database you might want a database class to handle connections. Then you'll want an entry class that handles viewing and adding entries. An administration class to handle administration, and a templating class. I would recommend, for a large project, to use a templating class like Smarty or patTemplate. These will save time and add powerful features you may not want to spend time programming yourself. The point is that you are coding a guestbook, not a template system. So use a template system, and get on with the guestbook. (Or forum, or CMS, or whatever.)
After you've decided on your classes, a good idea is to outline the classes and the functions in them. I'll give you an example here:
PHP Example: (!)

class Entry {

function Entry() {
//This function will include and initialize a global variable containing the database class
//Notice the class is named the same as this function. That means this function will run
//when the class is called
}

function view( $num, $start ) {
//This class will access the database and get the number of entries specified in $num, starting at the entry with the ID of
//$start
}

function post( $name, $email, $website, $aim, $yim, $msn, $icq, $title, $post ) {
//This class takes the information placed in it and adds it to the MySQL database
}

}

Obviously, more functions are needed for the class to work, and the coding is yet to be done, but the basic structure is there. Do this for all your classes and the work will be greatly simplified.
I haven't done everything necessary for planning -- there are still classes to plan out and stuff like that -- but this is an example of how it should be done. For your CMS or forum, or -- indeed -- guestbook, using this type of planning and structure will make your life easier, your coding better, and is the way to go if you are coding even a relatively smallish project.

Coding the Program -- Methods to make Coding Easier

Templating

It is extremely important to start out with a template and templating system. Everything you code will be built around this, so don't leave it to the end. I would recommend using the Smarty templating system, but if that fails go for patTemplate (another good system). But whatever you choose, or if you code it yourself, get it working before anything else. Because the template system is the main thing the end user will see and use, you need it to work. Not much about the structure, but one thing I would recommend doing is creating a template management class. Not a templating class that does the actual work, but one that manages it. So, say you are using Smarty, you would do something like:

PHP Example: (!)

class Template {

function Template( ) {
require_once("Smarty.php");
$smarty = new Smarty();
}
function showTpl( $tpl ) {
$smarty->display( $tpl );
}
}

You could do more, but even just this means that you can easily include the beginnings and ending of the Smarty code into every page without having to write it over and over.

Abstraction

What's abstraction? Well, it could be used as in "database abstraction", which means that this is a script that lets you use tons of different database utilities (MySQL, SQLite, PostGreSQL, etc.) without changing your code. But it also means something else. It means easy coding -- or at least easier. Look at it this way -- suppose you want something all over your pages to be the same. Well, either you can just write everything exactly the same over and over, or you can create another page that has the values you need and can be included into each page. The basic - or easiest - method of doing this is seen in sites that have several pages -- navbar.php, header.php, footer.php, etc. -- and include those pages into one that has the content. This type of thing is rendered obsolete by use of Smarty -- but you can go further -- especially for a large program.
One way is to create a messages class. "What messages?" you say. Well, whenever you do a program at some point you'll want to show a message -- whether it's "Thank you, your guestbook entry has been added to the database" or "Sorry, wrong username" -- and having a file like this will make it easier to have the same messages appear between scripts. An example script of this type would be:
PHP Example: (!)


class msg {

function msg( $num ) {
$start = "<p style="font-color:red">";
$end = "</p>";
$message = $start;
switch( $num ) {
case 1:
$message .= "Wrong username";
break;

case 2:
$message .= "Wrong pass";
break;
}
$message .= $end;
echo $message;
}
}

If you have a login page, you would access it like follows:
PHP Example: (!)

include "msg.php";
if( $pass != "arr" ) {
$msg = new msg( "2" );
}
elseif( $user != "user" ) {
$msg = new msg( "1" );
}

Obviously, that is not the correct way to create a login system, but you see how the message system could help. I included it as an example of a type of system that makes coding easier. So wherever you have a login, or somewhere where someone has to supply a username or password, just use the class and if you want to change the wording everywhere you have just one file to edit!
Not only that, if you need a new message, just add a new case inside the class, and then call it as you would the others. No need for echos, s, etc. If you are using a template system you can't put the templating for the message inside the class as I did, but if your template system supports this you can create a hidden sub-template that gets shown if the message class is called. Just 3 more lines of code in the message class is necessary for this using the Smarty system.
Now do you start to see what I mean by abstraction?
The only other important thing to cover in this is structure. Indent everything. Add a tab for each function in a class, and a tab for all the code inside that function, loop, or if statement.
And. . . COMMENT. Comment everything. You may think you'll know what you meant by a certain bit of code, but after a couple of months when the time comes to update. . .you'll be happier if you commented everything.

System!

If you look at this tutorial, you'll see my biggest point. System makes coding easier. If you have a system, anything can work, and probably will work much more easily. De-bugging is easier if you have different classes, and if you use templating systems along with classes your actual code will look cleaner and will update more easily.
Establish ways that you do certain things, and do things that way in every piece of code. Ever since I started thinking about this and programming using classes and tools like this my coding has taking huge leaps and bounds. Coding sloppily, on the other hand, may take less time initially (cutting out the planning and classes and suchlike), but when you go back to add new features, change a message, or change the template, you will pay for it.
If you are interested, try taking a simple application, and if you want to, try a bit of coding within the OOP environment using Smarty and a message class that employs Smarty's hidden/shown features. Just try out what I've outlined and see what you think. I practically guarantee that it will be much simpler after the planning stage to start programming, and that using classes for everything will make your life tons easier. If you don't know how to program OOP, check out a few tutorials (I will be writing one soon myself). It is worth the time.
There's obviously more to it that this, however, this tutorial covers some of the basic methods of planning. If you want to know how to design a database, look at the LAMP tutorial on this website. You can even find a tutorial here on message abstraction. However you do it, planning and system help. Hope this tutorial helped you

Windows XP Multiuser Remote Desktop

An interesting feature, on Windows XP, is the ability to be remote controlled from a second PC: the so called “Remote Desktop Connection” can be used from a dial-up connection or in a local ethernet network.

XP (and Media Center Edition), differently than the Server versions of Windows, has a limit: a single PC can be controlled by a single “local” user (the “real” person on place), OR a single “remote” user. If someone logs into the computer from remote, the local user is disconnected. The following procedure deactivates this block and allows multiple persons to connect and to use a single computer from remote.

Very useful, for example, if you’ve a very strong PC and you want your wife/friend/brother to use an old computer like a “terminal” to use applications on the new one, at the same time of you. Other application of the same technique: you’re at work and you want to connect to your home PC, without blocking your wife that is using the same computer to check email

UPDATE: it seems that XP is limited, also after this modification, to 3 concurrent users. So don’t waste time trying to raise the maximum number of connections over three (see step 5) because, at this time, I don’t think there’s a way to use the same XP PC with more than 3 persons at the same time (e.g. a local user and 2 remote users).

This procedure is an “hack”: do it at your own risk:


STEP 1

  • Start your Windows in Safe Mode (tap on F8 first of the Windows Loading Splash Screen);
  • click on “My Computer” with right mouse button and choose “Properties”;
  • go to “Remote” tab and uncheck “Allow users to connect remotely to this computer” (if it’s already unchecked, just do nothing);
  • click OK.
STEP 2
  • Go to Start -> Control Panel;
  • open “Administrative Tools” and then “Services”;
  • double click “Terminal Services”, in the list;
  • choose “Disabled” for “Startup Type” option;
  • click OK.
STEP 3
  • Go to C:\windows\system32\dllcache;
  • rename the termsrv.dll file to termsrv.original or another name you like;
  • copy into the folder this unrestricted old version of termsrv.dll;
  • go to C:\windows\system32 (the upper folder of the current one);
  • do the same operation: rename termserv.dll also here, and put another copy of the file I linked above.
STEP 4
  • Click Start, then “Run…”, type “regedit” (without quotes) and press ENTER;
  • navigate in the Windows Registry Tree to reach this path:
  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\Licensing Core;
  • click with right mouse button on blank space in the right part of the registry window, choose “New” > DWORD, name the new key “EnableConcurrentSessions” (without quotes), then edit it and set its value to 1;
  • close the editor.
STEP 5
  • Click Start, then “Run…”, type “gpedit.msc” (without quotes) and press ENTER;
  • open Computer Configuration > Administrative Templates > Windows Components > Terminal Services;
  • double click “Limit number of connections”, choose “Enabled” and set the maximum number of concurrent connections you want to allow (2 or more), then Restart Windows in normal mode.
STEP 6
  • Go back to Remote tab of My Computer’s properties (see step 1) and activate “Allow users to connect remotely to this computer”;
  • Go back to “Terminal services” in “Services” (see step 2) and set its “Startup type” to “Manual”
  • Now restart Windows. Your operating system should be ready to accept multiple remote desktop connections
  • Remember that you’ve to prepare different Windows Users for every “phisical” user that want to connect to your desktop, to autenticate with separate logins/passwords.
  • User accounts configuration is reachable in the control panel, and the list of users that can connect to the PC is editable in the remote tab of My computer.

Thursday, November 8, 2007

PHP 5.2.5 and MySQL 5.1

PHP 5.2.5 Released

On 08-Nov-2007 in php.net

The PHP development team would like to announce the immediate availability of PHP 5.2.5. This release focuses on improving the stability of the PHP 5.2.x branch with over 60 bug fixes, several of which are security related. All users of PHP are encouraged to upgrade to this release.

Further details about the PHP 5.2.5 release can be found in the release announcement for 5.2.5, the full list of changes is available in the ChangeLog for PHP 5.

Complete Source Code

PHP 5.2.5 (tar.bz2) [7,591Kb] - 08 November 2007md5: 1fe14ca892460b09f06729941a1bb605
PHP 5.2.5 (tar.gz) [9,739Kb] - 08 November 2007md5: 61a0e1661b70760acc77bc4841900b7a

Windows Binaries

PHP 5.2.5 zip package [9,713Kb] - 08 November 2007md5: a1e31c0d872ab030a2256b1cd6d3b7d1
PHP 5.2.5 installer [19,803Kb] - 15 November 2007md5: f9396b654721d9a18c95ea6412c3d54e

Note: Updated due to problems with the original installer for this release.

PECL 5.2.5 Win32 binaries [2,879Kb] - 08 November 2007md5: a3553b61c9332d08a5044cf9bf89f2df
PHP 5.2.5 Non-thread-safe Win32 binaries [9,619Kb] - 08 November 2007md5: 41ef1582f43cfdb6e546a626b9ef93d6
PECL 5.2.5 Non-thread-safe Win32 binaries [4,114Kb] - 08 November 2007md5: 6e5ac694907b4aae080b2c9b6e83748a

Note: (Most of these PECL extension files come standard with the PHP 4 Windows binaries, but have since been moved into this separate PECL download. Files such as php_pdf.dll, php_ssh2.dll, etc.)

MySQL 5.1 Downloads

MySQL Community Edition

MySQL Community Edition is a freely downloadable version of the world's most popular open source database that is supported by an active community of open source developers and enthusiasts.MySQL 5.1 Community Edition - Release Candidate Development Release

Click Here to download MySQL 5.1 Community Edition

NOTE: This release candidate release, as any other pre-production release, should not be installed on production level systems or systems with critical data. It is good practice to back up your data before installing any new version of software. Although MySQL has worked very hard to ensure a high level of quality, protect your data by making a backup as you would for any other pre release software. MySQL generally recommends that you dump and reload your tables from any previous version to upgrade to 5.1.

Thursday, November 1, 2007

What Is Web 2.0

Design Patterns and Business Models for the Next Generation of Software

The bursting of the dot-com bubble in the fall of 2001 marked a turning point for the web. Many people concluded that the web was overhyped, when in fact bubbles and consequent shakeouts appear to be a common feature of all technological revolutions. Shakeouts typically mark the point at which an ascendant technology is ready to take its place at center stage. The pretenders are given the bum's rush, the real success stories show their strength, and there begins to be an understanding of what separates one from the other.
The concept of "Web 2.0" began with a conference brainstorming session between O'Reilly and MediaLive International. Dale Dougherty, web pioneer and O'Reilly VP, noted that far from having "crashed", the web was more important than ever, with exciting new applications and sites popping up with surprising regularity. What's more, the companies that had survived the collapse seemed to have some things in common. Could it be that the dot-com collapse marked some kind of turning point for the web, such that a call to action such as "Web 2.0" might make sense? We agreed that it did, and so the Web 2.0 Conference was born.
In the year and a half since, the term "Web 2.0" has clearly taken hold, with more than 9.5 million citations in Google. But there's still a huge amount of disagreement about just what Web 2.0 means, with some people decrying it as a meaningless marketing buzzword, and others accepting it as the new conventional wisdom.
This article is an attempt to clarify just what we mean by Web 2.0.
In our initial brainstorming, we formulated our sense of Web 2.0 by example:
Web 1.0Web 2.0
DoubleClick--&gt;Google AdSense
Ofoto--&gt;Flickr
Akamai--&gt;BitTorrent
mp3.com--&gt;Napster
Britannica Online--&gt;Wikipedia
personal websites--&gt;blogging
evite--&gt;upcoming.org and EVDB
domain name speculation--&gt;search engine optimization
page views--&gt;cost per click
screen scraping--&gt;web services
publishing--&gt;participation
content management systems--&gt;wikis
directories (taxonomy)--&gt;tagging ("folksonomy")
stickiness--&gt;syndication
The list went on and on. But what was it that made us identify one application or approach as "Web 1.0" and another as "Web 2.0"? (The question is particularly urgent because the Web 2.0 meme has become so widespread that companies are now pasting it on as a marketing buzzword, with no real understanding of just what it means. The question is particularly difficult because many of those buzzword-addicted startups are definitely not Web 2.0, while some of the applications we identified as Web 2.0, like Napster and BitTorrent, are not even properly web applications!) We began trying to tease out the principles that are demonstrated in one way or another by the success stories of web 1.0 and by the most interesting of the new applications.

1. The Web As Platform

Like many important concepts, Web 2.0 doesn't have a hard boundary, but rather, a gravitational core. You can visualize Web 2.0 as a set of principles and practices that tie together a veritable solar system of sites that demonstrate some or all of those principles, at a varying distance from that core.

Web2MemeMap

Figure 1 shows a "meme map" of Web 2.0 that was developed at a brainstorming session during FOO Camp, a conference at O'Reilly Media. It's very much a work in progress, but shows the many ideas that radiate out from the Web 2.0 core.
For example, at the first Web 2.0 conference, in October 2004, John Battelle and I listed a preliminary set of principles in our opening talk. The first of those principles was "The web as platform." Yet that was also a rallying cry of Web 1.0 darling Netscape, which went down in flames after a heated battle with Microsoft. What's more, two of our initial Web 1.0 exemplars, DoubleClick and Akamai, were both pioneers in treating the web as a platform. People don't often think of it as "web services", but in fact, ad serving was the first widely deployed web service, and the first widely deployed "mashup" (to use another term that has gained currency of late). Every banner ad is served as a seamless cooperation between two websites, delivering an integrated page to a reader on yet another computer. Akamai also treats the network as the platform, and at a deeper level of the stack, building a transparent caching and content delivery network that eases bandwidth congestion.
Nonetheless, these pioneers provided useful contrasts because later entrants have taken their solution to the same problem even further, understanding something deeper about the nature of the new platform. Both DoubleClick and Akamai were Web 2.0 pioneers, yet we can also see how it's possible to realize more of the possibilities by embracing additional Web 2.0 design patterns.
Let's drill down for a moment into each of these three cases, teasing out some of the essential elements of difference.

Netscape vs. Google

If Netscape was the standard bearer for Web 1.0, Google is most certainly the standard bearer for Web 2.0, if only because their respective IPOs were defining events for each era. So let's start with a comparison of these two companies and their positioning.
Netscape framed "the web as platform" in terms of the old software paradigm: their flagship product was the web browser, a desktop application, and their strategy was to use their dominance in the browser market to establish a market for high-priced server products. Control over standards for displaying content and applications in the browser would, in theory, give Netscape the kind of market power enjoyed by Microsoft in the PC market. Much like the "horseless carriage" framed the automobile as an extension of the familiar, Netscape promoted a "webtop" to replace the desktop, and planned to populate that webtop with information updates and applets pushed to the webtop by information providers who would purchase Netscape servers.
In the end, both web browsers and web servers turned out to be commodities, and value moved "up the stack" to services delivered over the web platform.
Google, by contrast, began its life as a native web application, never sold or packaged, but delivered as a service, with customers paying, directly or indirectly, for the use of that service. None of the trappings of the old software industry are present. No scheduled software releases, just continuous improvement. No licensing or sale, just usage. No porting to different platforms so that customers can run the software on their own equipment, just a massively scalable collection of commodity PCs running open source operating systems plus homegrown applications and utilities that no one outside the company ever gets to see.
At bottom, Google requires a competency that Netscape never needed: database management. Google isn't just a collection of software tools, it's a specialized database. Without the data, the tools are useless; without the software, the data is unmanageable. Software licensing and control over APIs--the lever of power in the previous era--is irrelevant because the software never need be distributed but only performed, and also because without the ability to collect and manage the data, the software is of little use. In fact, the value of the software is proportional to the scale and dynamism of the data it helps to manage.
Google's service is not a server--though it is delivered by a massive collection of internet servers--nor a browser--though it is experienced by the user within the browser. Nor does its flagship search service even host the content that it enables users to find. Much like a phone call, which happens not just on the phones at either end of the call, but on the network in between, Google happens in the space between browser and search engine and destination content server, as an enabler or middleman between the user and his or her online experience.
While both Netscape and Google could be described as software companies, it's clear that Netscape belonged to the same software world as Lotus, Microsoft, Oracle, SAP, and other companies that got their start in the 1980's software revolution, while Google's fellows are other internet applications like eBay, Amazon, Napster, and yes, DoubleClick and Akamai.