Five tools for better PHP
Lorna Jane Mitchell takes a look beyond the code of our web applications and into some of the tools that make development process for LAMP (Linux, Apache, MySQL and PHP) slick and painless.
When we work on our applications, whatever our language of choice, sometimes we can focus too much on the code itself. A really good development lifecycle is about so much more than the code, it brings in a selection of supporting tools to ensure quality and reliability of the application, both as a standalone entity and as a living thing when it is deployed. To that end, this article looks at five tools to make for better PHP applications: PHP Code Sniffer, PHP Documentor, Supervisord, Phing and Uptime Robot to keep an eye on your delightfully robust and newly-deployed site.
01. PHP Code Sniffer
The first of these tools does start out rather close to the code, since PHP Code Sniffer is a tool for checking that code conforms to given coding standards. It ships with its own built-in rules, or you can very easily make your own. Using PHP Code Sniffer means that you can check that your project is consistent and readable throughout. PHP is whitespace-agnostic so the placement of brackets, new lines and indents don't affect the way that the code is parsed and run – so why bother with a tool like this?
Enforcing coding standards means ensuring a minimum standard of compliance and readability. It means that your whole project follows certain guidelines, making it easy to read and maintain. Given how much time the average web application spends in maintenance mode, that's a very important feature.
PHP Code Sniffer is available through PEAR and its project page is here. Assuming you have PEAR installed (if you don't use PEAR then check it out, there are some excellent tools in there!), you can install it using the following command:
pear install PHP_CodeSniffer
Once installed, you can immediately try checking the coding standards of your project against one of the installed standards. To see what's installed, use phpcs -i from the command line. My personal favourite is the Squiz standard, it's less draconian than PEAR but still pretty comprehensive. It's likely that (unless your project has already adopted coding standards) there will be a lot of warnings, so I find it useful to begin by generating a summary report. Run the following command from the directory that contains the project code:
phpcs --report=summary --standard=Squiz .
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
You'll see output that looks something like this:
It takes some time to go through and fix the various warnings, but it's well worth the effort, giving clean and readable code and paying attention to the quality of what we create as developers. If the sniffs that are bundled by default don't suit your needs, you can create your own! There is some great documentation available for doing this and it's quite an approachable task, particularly if you're happy to “pick and mix” from existing sniffs.
PHP Code Sniffer is especially powerful when it's part of an automated build process, so that there is a constant feedback loop on the state of the coding standards compliance. We'll revisit this later, when we look at Phing.
02. PHP Documentor
Making measurements and generating artifacts from code without actually running it's called static analysis. PHP Code Sniffer is one example of a static analysis tool, and PHP Documentor is another. PHP Documentor reads the structure of your code, the filesystem structure, the classes, functions and everything in between, and generates documentation from that. It gets even better when you add additional comments in specific notation to add further details about the various elements of the code.
Installation for PHP Documentor is via PEAR, so, once again, it's super-simple. However, PHP Documentor run its own PEAR channel, so there are two commands needed to install this tool:
pear channel-discover pear.phpdoc.org
pear install phpdoc/phpDocumentor-alpha
Once installed, you'll have a phpdoc program available on your command line. Tell phpdoc which folder to document with -t and where to write the output files -d. You can also customise the format of the output and the templates it uses, so you can create templates for your own organisation if appropriate.
As an example, look at this snippet from a TimeZone class (taken from the Joind.in event feedback site, which is open source, so all the code is on GitHub):
<?php
/**
* Class library to work with data/time issues for events/talks
*
* PHP version 5
*
* @category Joind.in
* @package Controllers
* @copyright 2009 - 2013 Joind.in
* @license http://github.com/joindin/joind.in/blob/master/doc/LICENSE JoindIn
* @link http://github.com/joindin/joind.in
*/
class Timezone
{
/**
* Get the current time at the event, where the event has a timezone offset
* of $evt_offset hours
*
* @param integer $evt_offset Offset for time
*
* @return integer
*/
public static function getEventTime($evt_offset)
{
$here = new DateTimeZone(date_default_timezone_get());
$hoffset = $here->getOffset(new DateTime("now", $here));
$off = (time() - $hoffset) + ($evt_offset * 3600);
return $off;
}
/**
* Returns a formatted version of getDatetimeFromUnixtime.
*
* @param integer $unixtime Unix time to format
* @param string $timezone Timezone to set for timestamp
* @param string $format Format to return
*
* @return string
*/
public static function formattedEventDatetimeFromUnixtime(
$unixtime,
$timezone,
$format
) {
$datetime = static::getDatetimeFromUnixtime($unixtime, $timezone);
$retval = $datetime->format($format);
return $retval;
}
}
When PHP Documentor is applied to this code snippet (there's more in the actual class than shown above), the result is something like this:
Running PHP Documentor even on a project without comments still gives an impression of the structure of the project and allows users to look at what is there. Any comments that are then added will appear in the output. This tool ties in quite nicely with the PHP Code Sniffer that was already mentioned because many of the PHP Code Sniffer standards require PHP Documentor comments to be present. Again, this tool works best when it's run regularly and automatically – it's common to have the API docs regenerate overnight or after each change is merged so that they stay up to date and useful as a reference.
03. Supervisord
Supervisord (pronounced “supervisor dee”) is one of those tools that you don't need until you write a particular style of application – and then you can't imagine how you lived without it. Web applications begin their life as a simple set of code serving responses to incoming requests. As they grow more complex, there are other tasks that need to take place either periodically or in response to a particular event. So how does Supervisord help?
Supervisord looks after long-running processes. If something crashes, Supervisord will try to restart the process; if the process keeps dying quickly, then Supervisord will give up. There are a few separate things that can commonly be found running under Supervisord on my own systems:
- IRC bots
- Worker scripts that pull jobs from a queue
- PHP/node.js applications serving requests from the command line
Supervisord is very easy to install on most platforms (via my package manager on my Linux system, for example) and comes with a control panel called SupervisorCTL. When I run it, I see something like:
From this, you can see that there are a bunch of processes running (some stopped) and how long they have all been running (I restarted my server yesterday!). This control panel gives me a way to check on things, to see the logged output of all the various tasks, and to stop, start or restart a worker. Long-running processes can be difficult to monitor and this tool makes that very easy. Once your application is beyond the serving web pages stage, Supervisord is your friend.
04. Phing
Phing is a build system along the same lines as Ant. It's a very simple, platform-independent way of running commands to run various jobs in your project. Many projects use it for deployment, but it can also perform any number of other tasks for you too, such as running test suites and using static analysis tools such as PHP Documentor and PHP Code Sniffer that were already mentioned in this post.
Phing is available via PEAR and has its own PEAR channel so you can install it along the same lines as the other PHP-based tools we've seen, using these commands:
pear channel-discover pear.phing.info
pear install phing/phing
Once it's there, again you have a new command available at your command line. Phing reads build files written in XML (very close to the Ant syntax, but not quite compatible), which can specify a number of 'targets', or commands that Phing knows how to run. Here's a small example:
<?xml version="1.0" encoding="UTF-8"?>
<project name="joindin" default="build" basedir=".">
<target name="phpdoc" description="Generate API documentation using PHPDocumentor">
<phpdoc2 destdir="${basedir}/build/api">
<fileset dir="${source}" />
</phpdoc2>
</target>
<target name="phplint" description="Run php -l over the fileset">
<phplint haltonfailure="true">
<fileset dir="${source}">
<patternset>
<include name="**/*.php"/>
</patternset>
</fileset>
</phplint>
</target>
<target name="build" depends="phpdoc, phplint"/>
</project>
This is a snippet from the Joind.in project again, from the build.xml file, which is how Phing is configured. If we consider each block in turn we first have a project tag that holds a default target name and sets the basedir property so that it can be used in the later elements. Within the project tag, there are a series of task tags. These are the tasks that Phing will be able to run and contain all the information needed to do so. The final target is 'build'. This is the default target for this project so will be run if the Phing command is run without arguments. This target depends upon two others, which means that these will also be run.
Phing gives clear command-line output, and generates artifacts such as the API documentation to be stored at given locations so that we can link to it later. Running the above from the command line gives output like this:
The output doesn't look like much, but if we check out what it wrote into the build directory, the API docs are there in full, along with artifacts from other build targets:
Phing really comes into its own for deployment. A series of tasks can be added into each target and these will be executed in turn. Phing supports all kinds of tasks (check out its documentation) including handling exports from version control, compressing and transferring files, and running commands over SSH.
Creating a Phing target for your project's automated deployment is a great way to make a potentially risky and complicated process very reliable. Rather than following the instructions on the wiki, Phing does all the steps that are needed to put your site live. Don't forget that this can also include restarting the worker scripts in your application via Supervisord!
05. Monitoring site health
Once your site is live, it's tempting to think that the job is done, but it's also very helpful to keep an eye on things. Monitoring doesn't mean waiting for your client to ring you and tell you when their site stops working. Instead, we use a tool to check at intervals that all is well, and let us know if it's not.
There are lots of options in this area, but we'll consider two kinds of monitoring: alert monitoring to let you know a site is down and trend monitoring where we can set thresholds for given, measured values. Alert monitoring is a very basic check on a website. If the site is there, everything is fine. If the site doesn't respond then it will alert you that there's a problem.
The simplest monitoring setup establishes that there's a successful HTTP response to a web request to a given URL. If there's no response, or an error response is received, then the site is considered to be 'down'. You can usually configure services that offer this kind of monitoring to contact you if this should happen by phone or email. One provider of this type of service is Uptime Robot, which allows easy monitoring of sites and also shows when sites were down, or not.
Using this service, we can also set up content monitoring. This checks that there's some element in the response that should be there. This helps to pick up when there is content being returned, but not the expected content (such as when you see the 'it works!' page from Apache). This can be something as simple as some text, which should appear on the page being monitored.
Sometimes you will see ping monitoring also, but it's quite possible for a machine to respond to ping, yet not be able to successfully serve HTTP responses. I prefer HTTP monitoring.
Trend monitoring looks at more complicated metrics, and often includes a tool running on the server itself. This may take into account the number of web server processes, the memory usage, or the response time of pages and track how those change over time. The monitoring tools will allow you to set thresholds where, if a particular piece of data trends too high or low, for a given period of time, you will be notified in some way. Sometimes that's paging the operations people, sometimes the dashboard screen in the corner will change colour; the right response depends entirely on your application.
06. Better tools
Improving our tools and processes takes an investment of time, and sometimes money as well. However, good tools enable every part of a development process to run smoothly and repeatably, and give great returns on the time we invest into making them better. This article aimed to include a selection that you may not already be making use of, but which are an asset to a pain-free development process.
Lorna is an independent web development consultant, trainer and author based in Leeds, UK. She is a PHP specialist and works with teams to get the most out of their applications, their tools, and their people. Lorna is a regular conference speaker and lead developer at the Joind.in open source project.
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of eight full-time members of staff: Editor Georgia Coggan, Deputy Editor Rosie Hilder, Ecommerce Editor Beren Neale, Senior News Editor Daniel Piper, Editor, Digital Art and 3D Ian Dean, Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Beth Nicholls and Staff Writer Natalie Fear, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.