5 tools for better PHP

5 tools for better PHP

Taking 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

by Janeth Kent Date: 11-04-2013

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.

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:

1.	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:

1.	phpcs -- report = summary -- standard = Squiz

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.

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:

	
				1.	pear channel - discover pear.phpdoc.org

			
				2.	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):

	
  1. <?php
  2.  
  3. /**
  4.  * Class library to work with data/time issues for events/talks
  5.  *
  6.  * PHP version 5
  7.  *
  8.  * @category  Joind.in
  9.  * @package   Controllers
  10.  * @copyright 2009 - 2013 Joind.in
  11.  * @link      http://github.com/joindin/joind.in
  12.  */
  13. class Timezone
  14. {
  15.  
  16.     /**
  17.      * Get the current time at the event, where the event has a timezone offset
  18.      * of $evt_offset hours
  19.      *
  20.      * @param integer $evt_offset Offset for time
  21.      *
  22.      * @return integer
  23.      */
  24.     public static function getEventTime($evt_offset)
  25.     {
  26.         $here    = new DateTimeZone(date_default_timezone_get());
  27.         $hoffset = $here->getOffset(new DateTime("now", $here));
  28.         $off     = (time() - $hoffset) + ($evt_offset * 3600);
  29.         return $off;
  30.     }
  31.  
  32.     /**
  33.      * Returns a formatted version of getDatetimeFromUnixtime.
  34.      *
  35.      * @param integer $unixtime Unix time to format
  36.      * @param string  $timezone Timezone to set for timestamp
  37.      * @param string  $format   Format to return
  38.      *
  39.      * @return string
  40.      */
  41.     public static function formattedEventDatetimeFromUnixtime(
  42.         $unixtime,
  43.         $timezone,
  44.         $format
  45.     ) {
  46.         $datetime = static::getDatetimeFromUnixtime($unixtime, $timezone);
  47.         $retval   = $datetime->format($format);
  48.  
  49.         return $retval;
  50.     }
  51. }

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.

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.

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:

 

		 1. pear channel

	     2. pear install 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:

		
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project name="joindin" default="build" basedir=".">
  3.  
  4.  <target name="phpdoc" description="Generate API documentation using PHPDocumentor">
  5.   <phpdoc2 destdir="${basedir}/build/api">
  6.    <fileset dir="${source}" />
  7.   </phpdoc2>
  8.  </target>
  9.  
  10.  <target name="phplint" description="Run php -l over the fileset">
  11.    <phplint haltonfailure="true">
  12.      <fileset dir="${source}">
  13.        <patternset>
  14.          <include name="**/*.php"/>
  15.        </patternset>
  16.      </fileset>
  17.    </phplint>
  18.  </target>
  19.  
  20.  <target name="build" depends="phpdoc, phplint"/>
  21. </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!

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.

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.

 

 
by Janeth Kent Date: 11-04-2013 hits : 3298  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.