70
511
Writing Maintainable Code
Variable names shoulddescribe the data they contain.If you are storing somebody’s sur-
name,call it
$surname
.You need to find a balance between length and readability.For
example,storing the name in
$n
makes it easy to type,but the code is difficult to under-
stand.Storing the name in
$surname_of_the_current_user
is more informative,but it’s
a lot to type (and therefore easier to make a typing error) and doesn’t really add that
much value.
You need to make a decision on capitalization.Variable names are case sensitive in
PHP,as we’ve mentioned previously.You need to decide whether your variable names will
be all lowercase,all uppercase,or a mix—for example,capitalizing the first letters of
words.We tend to use all lowercase because this scheme is the easiest to remember for us.
Distinguishing between variables and constants with case is also a good idea.A com-
mon scheme is to use all lowercase for variables (for example,
$result
) and all uppercase
for constants (for example,
PI
).
One bad practice some programmers use is to have two variables with the same name
but different capitalization just because they can,such as
$name
and
$Name
.We hope it is
obvious why this practice is a terrible idea.
It is also best to avoid amusing capitalization schemes such as
$WaReZ
because no one
will be able to remember how it works.
You should also think about what scheme to use for multiword variable names.For
example,we’ve seen all the following schemes:
$username
$user_name
$userName
It doesn’t matter which you opt for,but you should try to be consistent about usage.You
might also want to set a sensible maximum limit of two to three words in a variable
name.
Function names have manyof the same considerations,with a couple of extras.
Function names should generally be verb oriented.Consider built-in PHP functions
such as
addslashes()
or
mysql_connect()
,which describe what they are going to do
to or with the parameters they are passed.This naming scheme greatly enhances code
readability.Notice that these two functions have a different naming scheme for dealing
with multiword function names.PHP’s functions are inconsistent in this regard,partly as
a result of having been written by a large group of people,but mostly because many
function names have been adopted unchanged from various different languages and
APIs.
Also remember that function names are not case sensitive in PHP.You should proba-
bly stick to a particular format anyway,just to avoid confusion.
You might want to consider using the module-naming scheme used in many PHP
modules—that is,prefixing the name of functions with the module name.For example,
all the improved MySQL functions begin with
mysqli_
,and all the IMAP functions
begin with
imap_
.If,for example,you have a shopping cart module in your code,you
could prefix the function in that module with
cart_
.
50
512
Chapter 24 4 Using PHP and MySQL for Large Projects
Note,however,that when PHP5 provides both a procedural and an object-oriented
interface,the function names are different.Usually,the procedural ones use underlines
(
my_function()
) and the object-oriented ones use what are called studlyCaps
(
myFunction()
).
In the end,the conventions and standards you use when writing code don’t really
matter,as long as you apply some consistent guidelines.
Commenting Your Code
All programs should be commented to a sensible level.You might ask what level of com-
menting is sensible.Generally,you should consider adding a comment to each of the fol-
lowing items:
n
Files,whether complete scripts or include files—Each file should have a
comment stating what this file is,what it’s for,who wrote it,and when it was
updated.
n
Functions—Function comments should specify what the function does,what
input it expects,and what it returns.
n
Classes—Comments should describe the purpose of the class.Class methods
should have the same types and levels of comments as any other functions.
n
Chunks of code within a script or function—We often find it useful to write
a script by beginning with a set of pseudocode-style comments and then filling in
the code for each section.So an initial script might resemble this:
<?
// validate input data
// send to database
// report results
?>
This commenting scheme is quite handy because after you’ve filled in all the sec-
tions with function calls or whatever,your code is already commented.
n
Complex code or hacks—When performing some task takes you all day,or you
have to do it in a weird way,write a comment explaining why you used that
approach.This way,when you next look at the code,you won’t be scratching your
head and thinking,“What on earth was thatsupposed to do?”
Here’s another general guideline to follow:Comment as you go.You might think you will
come back and comment your code when you are finished with a project.We guarantee
you this will not happen,unless you have far less punishing development timetables and
more self-disciplinethan we do.
Indenting
As in any programming language,you should indent your code in a sensible and consis-
tent fashion.Writing code is like laying out a resumé or business letter.Indenting makes
your code easier to read and faster to understand.
50
513
Writing Maintainable Code
In general,any program block that belongs inside a control structure should be
indented from the surrounding code.The degree of indenting should be noticeable (that
is,more than one space) but not excessive.We generally think the use of tabs should be
avoided.Although easy to type,they consume a lot of screen space on many people’s
monitors.We use an indent level of two to three spaces for all projects.
The way you lay out your curly braces is also an issue.The two most common
schemes follow:
Scheme 1:
if (condition) {
// do something
}
Scheme 2:
if (condition)
{
// do something else
}
Which one you use is up to you.The scheme you choose should,again,be used consis-
tently throughout a project toavoid confusion.
Breaking Up Code
Giant monolithic codeis awful.Some people create one huge script that does every-
thing in one giant switch statement.It is far better to break up the code into functions
and/or classes and put related items into include files.You can,for example,put all your
database-related functions in a file called
dbfunctions.php
.
Reasons for breaking up your code into sensible chunks include the following:
n
It makes your code easier to read and understand.
n
It makes your code more reusable and minimizes redundancy.For example,with
the previous
dbfunctions.php
file,you could reuse it in every script in which
you need to connect to your database.If you need to change the way this works,
you have to change it in only one place.
n
It facilitates teamwork.If the code is broken into components,you can then assign
responsibility for the components to team members.It also means that you can
avoid the situation in which one programmer is waiting for another to finish
working on
GiantScript.php
so that she can go ahead with her own work.
At the start of a project,you should spend some time thinking about how you are going
to break up a project into planned components.This process requires drawing lines
between areas of functionality,but you should not get bogged down in this because it
might change after you start working on a project.You also need to decide which com-
ponents need to be built first,which components depend on other components,and
what your timeline will be for developing all of them.
40
514
Chapter 24 4 Using PHP and MySQL for Large Projects
Even if all team members will be working on all pieces of the code,it’s generally a good
idea to assign primary responsibility for each component to a specific person.Ultimately,
this person would be responsible if something goes wrong with her component.Someone
should also take on the job of build manager—that is,the person who makes sure that all
the components are on track and working with the rest of the components.This person
usually also manages version control;we discuss this task more later in the chapter.This
person can be the project manager,or this task can be allocated as a separate responsibility.
Using a Standard Directory Structure
When starting a project,you need to think about how your component structure will be
reflected in your website’s directory structure.Just as it is a bad idea to have one giant
script containing all functionality,it’s also usually a bad idea to have one giant directory
containing everything.Decide how you are going to split up your directory structure
between components,logic,content,and shared code libraries.Document your structure
and make sure that all the people working on the project have a copy so that they can
find what they need.
Documenting and Sharing In-House Functions
As you develop function libraries,you need to make them available to other program-
mers on your team.Commonly,every programmer on a team writes his own set of
database,date,or debugging functions.This scheme is a time waster.You should make
functions and classes available to others.
Remember that even if code is stored in an area or directory commonly available to
your team members,they won’t know it’s there unless you tell them.Develop a system
for documenting in-house function libraries and make it available to programmers on
your team.
Implementing Version Control
Version controlis the art t of concurrent change management as applied to software devel-
opment.Version control systems generally act as a centralrepositoryor archive and supply
a controlled interface for accessing and sharing your code (and possibly documentation).
Imagine a situation in which you try to improve some code but instead accidentally
break it and can’t roll it back to the way it was,no matter how hard you try.Or you or a
client decides that an earlier version of the site was better.Or you need to go back to a
previous version for legal reasons.
Imagine another situation in which two members of your programming team want to
work on the same file.They both might open and edit the file at the same time,over-
writing each other’s changes.They both might have a copy that they work on locally
and change in different ways.If you have thought about these things happening,one
programmer might be sitting around doing nothing while she waits for another to finish
editing a file.
40
515
Implementing Version Control
You can solve all these problems with a version control system.Such systems can
track changes to each file in the repository so that you can see not only the current state
of a file,but also the way it looked at any given time in the past.This feature allows you
to roll back broken code to a known working version.You can tag a particular set of file
instances as a release version,meaning that you can continue development on the code
but get access to a copy of the currently released version at any time.
Version control systems also assist multiple programmers in working on code togeth-
er.Each programmer can get a copy of the code in the repository (called checking it out)
and when he makes changes,these changes can be merged back into the repository
(checked inor committed).Version control systems can therefore track who made each
change to a system.
These systems usually have e a facility for managing concurrent updates.This means
that two programmers can actually modify the same file at the same time.For example,
imagine that John and Mary have both checked out a copy of the most recent release of
their project.John finishes his changes to a particular file and checks it in.Mary also
changes that file and tries to check it in as well.If the changes they have made are not in
the same part of the file,the version control system will merge the two versions of the
file.If the changes conflict with each other,Mary will be notified and shown the two
different versions.She can then adjust her version of the code to avoid the conflicts.
The version control systemused by the majority of Unix and/or open source devel-
opers is the Concurrent Versions System (CVS).CVS,which is open source,comes bun-
dled with virtually every version of Unix,and you can also get it for PCs running DOS
or Windows and Macs.It supports a client/server model so that you can check code in
or out from any machine with an Internet connection,assuming that the CVS server is
visible on the Internet.It is used for the development of PHP,Apache,and Mozilla,
among other high-profile projects,at least in part for this reason.
You can download CVS for your systemfrom the CVS home page at
http://www.cvshome.org/
Although the base CVS system is a command-line tool,various add-ons give it a more
attractive front end,including Java-based and Windows front ends.You can also access
them from the CVS home page.
Bitkeeper is a rival version control product,used by a few high-profile open source
projects including MySQL and the Linux kernel.It is available free to open source
projects.
Commercial alternatives are also available.One of them is perforce,which runs on
most common platforms and has PHP support.Although it is commercial,free licenses
are offered for open source projects from the website at
http://www.perforce.com/
40
516
Chapter 24 4 Using PHP and MySQL for Large Projects
Choosing a Development Environment
This discussion of version controlbrings up the more general topic of development
environments.All you really need are a text editor and browser for testing,but program-
mers are often more productive in an Integrated Development Environment (IDE).
You can find a number of emerging free projects to build a dedicated PHP IDE,
including KPHPDevelop,for the KDE desktop environment under Linux,available from
http://kphpdev.sourceforge.net/
Currently,though,the best PHP IDEs are all commercial.Zend Studio from zend.com,
Komodo from activestate.com,and PHPEd from nusphere.com provide
feature-rich IDEs.All have a trial download but require payment for ongoing use.
Komodo offers a cheap noncommercial use license.
Documenting Your Projects
You can produce manydifferent kinds of documentation for your programming projects,
including,but not limited to,the following:
n
Design documentation
n
Technical documentation/developer’s guide
n
Data dictionary (including class documentation)
n
User’s guide (although most web applications have to be self-explanatory)
Our goal here is not to teach you how to write technical documentation but to suggest
that you make your life easier by automating part of the process.
Some languages enable you to automatically generate some of these documents—par-
ticularly technical documentation and data dictionaries.For example,javadoc generates a
tree of HTML files containing prototypes and descriptions of class members for Java
programs.
Quite a few utilities of this type are available for PHP,including
n
phpdoc,availablefrom http://www.phpdoc.de/
This system is used by PEAR for documenting code.Note that the term phpDocis
used to describe several projects of this type,of which this is one.
n
PHPDocumentor,available from http://phpdocu.sourceforge.net
PHPDocumentor gives similar output to javadoc and seems to work quite robust-
ly.It also seems to have a more active developer team than the other two listed
here.
Documents you may be interested
Documents you may be interested