Posts Tagged PHP

PHP Development in Eclipse

I used Eclipse on a Mac to work with Java during my PhD, so familiarity made it seem the logical choice for some recent PHP development I've been doing. This post runs through the various plugins I added to support the development process, including checking code quality, running unit tests, and creating documentation.

The first step is obviously to install Eclipse. To ensure compatibility with all the plugins mentioned, I found it necessary to download the standard version of Eclipse and then install the PDT tools afterwards. The dedicated all-in-one PDT version of Eclipse didn't play ball with everything I needed it to.

 

Version Control – Subclipse
I use Subversion (SVN) for version control, and Subclipse seems to to be the de-facto client for Eclipse. However, there are some pitfalls to be aware of. If you install Subclipse and then try to add a respository in the SVN Perspective, you may get an error telling you that you need version 1.7 or higher of the JavaHL library. This is part of the Subversion binary, so your copy of SVN must be out of date. If you nip over to Collabnet for the latest version you'll find that they only have 1.6, so instead you'll need to visit WANDisco. Once 1.7 is installed, you should then be able to connect with Subclipse using the JavaHL library. Thanks to peeps on Stackoverflow for pointing this out.

Unfortunately JavaHL still failed for me, telling me that the network connection closed unexpectedly. I tried to use the SVNKit adapter instead of JavaHL, but it turns out that SVNKit isn't supported in version 1.8 of Subclipse, (the most recent version). I therefore uninstalled Subclipse v1.8 and installed v1.6 instead. That still didn't work because apparently SVNKit doesn't currently support SVN 1.7 (see previous link). Anyway, this turned out to be all a bit misleading, because when I tried it everything just worked.

 

Debgugging – Xdebug
If you want to debug PHP, then you'll need either Xdebug or Zend Debugger. I chose the former for reasons I can't quite recall. But setting it up required the following steps in Eclipse:

  1. In Preferences > PHP > PHP Executables, set up your PHP executable. Mine, the default Lion version, was at /usr/bin/php, and php.ini was at /etc/php.ini
  2. In Preferences > PHP >  PHP Servers, set up your PHP server. I had to delete the "default" one first.
  3. In Preferences > PHP > Debug, set your debugger, server and executable.
  4. If you've changed the Xdebug port from the default of 9000 for any reason (I had problems with my initial Xdebug install, and that was one of the suggested fixes), don't forget to correct it in Preferences > PHP > Debug > Installed Debuggers.

 

Debugging with Xdebug. The 'debug' panel shows the methods which are currently running, while the relevant code is shown below. Panel on the right shows variables and their current values.

Debugging with Xdebug. The 'debug' panel shows the methods which are currently running, while the relevant code is shown below. Panel on the right shows variables and their current values.


Coding Standards – PHP Code Sniffer

To ensure that your code is up to standard(s), you can install PHP_CodeSniffer with PEAR:

pear install PHP_CodeSniffer

There's more detail on their homepage, including information on the –report flag to get a summary of the errors in your entire project instead of all the detail for every file. I'd recommend creating your own customised standard so you can exclude errors you're not bother about (variables with single-letter names, for example). Once you've done that, you can also make your standard the default to be used each time you run PHPCS.

PHP Code Sniffer summary report.

PHP Code Sniffer summary report.


Coding Problems – PHP Mess Detector

PHP Mess Detector does a good job of finding nasty bits of code. This includes 'dead' code that's never run, complicated loops / nested ifs,  It's worth reading the section on how to create a custom ruleset, because the defaults may include tests that you want to exclude.


Unit Testing – PHPUnit

Unit testing is a great habit to get into, and test-driven development takes this to its logical conclusion. PHPUnit and SimpleTest both provide unit testing in PHP; I chose PHPUnit because there seemed to be more material online about how to use it. To install PHPUnit you can use PEAR. Unfortunately PEAR wasn't installed on my Lion system, but you can install it using wget.  Unfortunately wget wasn't installed on my Lion system, but you can install it with a number of terminal commands.

Once wget is installed and then PEAR is installed and then PHPUnit is installed (!), you can set up Eclipse to run it as an external tool. However, it's much nicer to get it integrated into your Eclipse installation. To do this, I used MakeGood. The instructions on their website are pretty easy to follow and essentially boil down to:

  1. Install the MakeGood plugin from within Eclipse, using http://eclipse.piece-framework.com as the URL
  2. DON'T  ignore the lines about having to specify a PHP executable; I did (because I already had an executable defined), but for some reason the executable had disappeared from my Eclipse preferences and so I had to add it again after much head-scratching.
  3. DO display the MakeGood 'view' in your Eclipse window as soon as possible – it has a nice little message which explains what might be stopping you running your tests.
  4. A message about Stagehand_Testrunner led me to install that separately, using PEAR (instructions are on the Stagehand website)
  5. Despite adding my PEAR folder as a library to the project build path, I was still getting a message saying that PHPUnit_Framework_TestCase could not be found when I ran a test. I resolved this by adding /Users/Haydn/pear/share/pear/PHPUnit to the build path too, and using require_once in the test class:  require_once 'PHPUnit/Autoload.php';
MakeGood showing a successful test in Eclipse.

MakeGood showing a successful test in Eclipse.

Once PHPUnit is working correctly, if you want to test database operations too then you'll need the DbUnit extension. There's extensive help regarding this whole subject area in the PHP Unit manual. Note that SQL Server isn't supported by default.

 

Documentation – PHPDoc
If you're documenting your code then you'll want phpdoc – installation instructions are on their website. Just use the two PEAR commands on their homepage, and ignore other websites (which generally omit the '-alpha' reference). If you try and generate some documentation but get an error about GraphViz not being installed ("Unable to find the `dot` command of the GraphViz package. Is GraphViz correctly installed and present in your path?"), go to the GraphViz website to download a .pkg file for Lion and install it. If you get a message about timezones, ensure that the correct one is set in your php.ini file (e.g. date.timezone = Europe/London).

 

Automation – ANT
Once all the above are in place, it's nice to be able to run them all together. You can use ANT to do this; here's an example of my ANT build.xml file:
<?xml version="1.0"?>
<!DOCTYPE project>
<project name="MyProject" default="test">
    <property name="docs_dir" value="docs" />
    <property name="log_file" value="MyLogFile.log" />
    <target name="dtd" description="Creates a DTD for this build.xml file.">
        <antstructure output="project.dtd"/>
    </target>
    <target name="clean" description="Deletes temporary and compiled files.">
        <delete dir="${docs_dir}"/>
        <delete dir="output"/>
    </target>
    <target name="messdetect" description="Runs PHP Mess Detector on PHP files.">
        <exec executable="/Users/Haydn/pear/bin/phpmd" failonerror="true">
            <arg value="." />
            <arg value="text" />
            <arg value="anciliary/PHPMD_custom_ruleset.xml" />
        </exec>
    </target>
    <target name="codesniff" description="Runs PHP Code Sniffer on PHP files.">
        <exec executable="/Users/Haydn/pear/bin/phpcs" failonerror="true">
            <arg value="." />
            <arg value="--standard=MyStandard" />
            <arg value="--extensions=php" />
            <arg value="--report=summary" />
        </exec>
    </target>
    <target name="test" description="Runs all PHPUnit tests.">
        <exec executable="/Users/Haydn/pear/bin/phpunit" failonerror="true">
            <arg value="test" />
        </exec>
    </target>
    <target name="document"  depends="clean" description="Generates documentation for PHP files.">
        <exec executable="/Users/Haydn/pear/bin/phpdoc" failonerror="true">
            <arg value="-d" />
            <arg value="." />
            <arg value="-t" />
            <arg value="${docs_dir}" />
        </exec>
    </target>
    <target name="build" depends="clean,messdetect,codesniff,test,document" description="Run everything.">
    </target>
</project>
Next?
The next step is to move to continuous integration, using packages like Cruise Control or phpUnderControl, which will automatically test and build your code on a regular schedule. As a one-man project I always know the status of my work, so that's not been necessary so far. Hopefully the above will be of help in getting you up-and-running with a decent PHP development workflow in Eclipse.

Tags: , , , , , , , , , , , , , ,

UHS5 – LAMP web server + WordPress

The process is covered in quite a lot of good detail in the Ubuntu Documentation, but I've summarised the main steps below for those who just want to get up and running with the basics.

Apache

We can again use apt-get, this time to install Apache HTTP server. It's version 2 which is available now, hence the command is:

sudo apt-get install apache2

The marvellous apt-get takes care of installing all dependancies too, so anything else we might need to run apache just gets added without us having to worry about it. Once the install process is finished, navigate to http://localhost and make sure that you can see the default Apache page.

To make the pages visible from other machines on the local network, you'll need to edit /etc/apache2/sites-available/default. Find the line:

Allow from 127.0.0.0/255.0.0.0 ::1/128

and add the IP addresses of other local machines onto the end. Although all our PCs have static IP addresses, I used a wildcard so that things like my iPhone and visiting friend's PCs can also access the server. I therefore changed the line from the above to:

Allow from 127.0.0.0/255.0.0.0 ::1/128 192.168.1.*

The pages served by default, in my case at least, were stored in /var/www. If you want to run more than one website through Apache, a guide on zaphu.com describes how to add a new site and activate it.

PHP

PHP is pretty easy to install:

sudo apt-get install php5

That's it! The system will probably re-start Apache for you at the appropriate places, but if you want to check whether it's successfully integrated PHP5 support into Apache, then running the following will give you an answer as to whether or not the relevant module has been enabled:

[code lang="bash"]>sudo a2enmod php5[/code]

MySQL

To install MySQL, just run:

[code lang="bash"]sudo apt-get install mysql-client mysql-server[/code]

During the setup procedure, you'll be asked to choose a password for the 'root' account. Once that's installed, ensure you've got support for MySQL in PHP:

[code lang="bash"]sudo apt-get install php5-mysql[/code]

And finally, if you want a GUI admin tool, then MySQL Administrator does a fine job (although it seems to have been replaced by MySQL Workbench now, but I couldn't find that using apt-get), or you can use PHPMyAdmin to do it in your browser:

[code lang="bash"]sudo apt-get install mysql-admin sudo apt-get install phpmyadmin[/code]

If you want to check the server's working OK, log in to it using the root account we set up during installation:

[code lang="bash"]mysql -u root -p[/code]

Obviously the next thing you'll do is set about creating a new user account and locking down the 'root' account, right? Good, I thought so.

WordPress

You can WordPress installation files and manually unpack them if you want, but I chose to install by checking out the latest stable version from the WordPress repository using Subversion. This will make it very easy to upgrade in future, by just 'switching' to the newest tag release. Note that this assumes you've already installed Subversion on your system – if not, please see my post detailing this first. Installing WordPress in this manner is something else that's incredibly easy – just one command. Make sure you run this command from whatever directory you want WordPress to be installed into – apache2 sets the default web directory to be /var/www, so I'd suggest starting there. The command to checkout ("co") a specific version of WordPress (3.1.3 in this case) is:

[code lang="bash"]sudo svn co http://core.svn.wordpress.org/tags/3.1.3 .[/code]

Note the trailing full-stop, which specifies that the files should be checked out to the current directory. This whole process is discussed in more depth in the relevant page of the official WordPress.org documentation. Once you've installed the actual files, you'll need to set up a database for WordPress to use. I'd include the command here but unfortunately each time I type it in, my WordPress installation thinks I'm trying a SQL injection attack and I get locked out of my own domain! There's plenty of documentation out and about which covers this though. Set up a user for the blog too, which has the necessary permissions to work with the database you've created. Finally, copy wp-config-sample.php to a new file called wp-config.php and set up the values as required. You can view the site by navigating to http://localhost and answering a couple of questions to complete the installation, but don't forget to change the "WordPress URL" in the settings screen to something like "http://myshinynewserver", otherwise you may find that the site is served up with references to "localhost" in, instead of your server. After that, you should be good to go. Except, that is, if you're afflicted by…

The WordPress Blank Screen of Death

I carried out all the steps above, but when I tried to view my shiny new blog, all I got was a blank page. The HTML source for the page was blank too. There are hundreds of different explanations, articles and blog posts which offer advice on how to rectify it. None of them worked for me. I did however, find that in my case there was a very simple solution. I enabled debugging in WordPress by adding the following line to wp-config.php:

[code lang="php"]define('WP_DEBUG', true);[/code]

This gave me the following message when I checked the subsequent output in /var/log/apache2/error.log:

[code lang="bash">[Fri Jun 17 22:00:25 2011] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected ':' in /var/www/wp-config.php on line 25[/code]

Line 25 is the line which contains the password for the relevant MySQL database. All of my passwords are generated by the GRC Ultra High Security Password Generator, and include symbols. This didn't pose any problems when I set up the user account with MySQL Administrator, but it did include a colon which was enough to completely confuse PHP. This was preventing the system connecting to the database and causing the blank screen of death. I amended the password so it didn't contain a colon any more, and suddenly everything instantly worked again. Once you've found your error, don't forget to turn debugging off again.

Tags: , , , , , , , , , , , , , , , ,

Eclipse Ganymede / PHP / SVN

The Eclipse Foundation yesterday released the latest version of the Eclipse IDE, named Ganymede (press release). This is the first attempt at synchronising the release of a new version of the IDE with new versions of plug-ins and 23 of the ~90 registered plug-ins have managed to come up with new releases alongside the main IDE.

Eclipse Ganymede splash screen

I use Eclipse for a few different things, including writing in Java, HTML, JavaScript, PHP and LaTeX. I downloaded and installed the JEE version of Eclipse, which obviously supports Java straight out of the box, along with HTML and Javascript (which you can now format automatically). However, in the Europa release of Eclipse I use the PDT project plug-in to support coding with PHP. The PDT set of tools isn't included by default with Ganymede. Unfortunately, the current release doesn't work on Ganymede, and there are no plans to release a new version until 15 September 2008. That means I'm going to have to stick with Europa for PHP until then, and I'm inclined to just use it for everything, rather than have two versions of Eclipse going on my machine. EDIT: Sasha has posted a comment linking to this page on the PDT Wiki, which details how you can get Ganymede playing nicely with the current version of PDT.

I haven't even tried to installed TeXlipse yet! EDIT: v1.2.0 of Texlipse installed OK, and will highlight syntax and show document outlines correctly. However, I've not been able to make it compile anything. A colleague at work had the same problem with Texlipse and Europa, while I never did, so this might be machine-specific.

First impressions of Ganymede are pretty good anyway, with the main exciting feature being built-in SVN support through the bundled Subversive plug-in. Well, to a degree at least. Before I could connect to our repository here at work, I had to install an SVN Connector from the following update URL in Eclipse:

http://www.polarion.org/projects/subversive/download/eclipse/2.0/update-site/

I initially tried the JavaHL connector, but then actually read the documentation on this page, which states that JavaHL is "win32 only". So, I subsequently installed the SVNKit 1.4.something release (1.5.0 is available, but is an RC not a full version) and everything worked fine.

New view of Subversion repository through Subversive

First impressions of Subversive are good, with the software automatically knowing which folders are trunks, branches, tags, etc., and setting icons accordingly. I've not yet done any merging, but there seem to be big GUI improvements there over the previous SVN plug-in I was using (Subclipse). Subversive seems to be playing fine with our SVN server in general.

There's a good summary of the changes in Java on the Eclipse help site. For example, "Code clean up on save" lets you perform certain actions each time a file is saved, such as formatting the code, and removing trailing whitespace. There have been loads of improvements to Content Assist (the bit that tries to auto-complete code for you), which I won't detail here, but they're worth looking at. There's now a "Template for adding JUnit 4 test methods", although I've not tried it yet. In fact, there's so many improvements I'm going to just give you that same link again, and urge you to check it out.

So overall, Ganymede seems pretty good, and there are definitely some features in there which I think will prove useful. Roll on September and the availability of PHP in there, and I'll be a very happy bunny.

Tags: , , , , , , , , , , , , , , ,