Resque is a popular Redis-backed Ruby library for creating and processing background jobs, this is all well and good if you’re building applications in Ruby but fortunately for those, like me, who prefer PHP there is also a PHP port - PHP-Resque. This post will describe how to use php-resque in conjunction with the Silex micro framework to queue jobs, initially this was not immediately obvious to me as php-resque is not namespaced so wouldn’t work using the default autoloading configuration but fortunately the class naming seems to follow the PEAR convention where the path to the class is defined by the classname (i.e. Resque_Event would be found in Resque/Event.php). The method described here should work for any similar libraries.
One point to note, there is a Symfony2 bundle that could be easily integrated with Silex which aims to integrate php-resque but it’s a lot more complicated than I require and in most cases is just not necessary.
The key to using php-resque is to use the registerPrefix method of the symfony classloader (included with Silex) which uses PEAR naming conventions load libraries.
To configure php-resque first clone a copy of the library from github into the vendors folder (or wherever you like to store your external libraries):
Now we have the library in place where ever you configure your application, in my case /src/bootstrap.php which is included in the main application file point the Synfony class loader to the place for classes beginning with the prefix Resque, all the relevant php-resque files are in the lib subdirectory:
Silex is a great platform for building small web applications and APIs, recently I’ve been using it to build an API with only a couple of routes. As this API will only be used by a couple of users it made sense to use use HTTP basic auth (over SSL of course). HTTP auth could be left to apache/nginx etc. but that wouldn’t give me the control I’d like over the output and authentication so I implemented it in Silex, I hope someone finds this useful:
HTTP basic authentication is very simple and just passes a username and password in the headers, PHP has built in functionality to extract these values which can be used in the Silex before hook to ensure it happens before every request is fulfilled, my example is for an API which returns JSON but it would work equally well for a conventional website:
$app->before(function() use ($app)
{
if (!isset($_SERVER['PHP_AUTH_USER']))
{
header('WWW-Authenticate: Basic realm="<website name>"');
return $app->json(array('Message' => 'Not Authorised'), 401);
}
else
{
//once the user has provided some details, check them
$users = array(
'workflow' => 'password'
);
if($users[$_SERVER['PHP_AUTH_USER']] !== $_SERVER['PHP_AUTH_PW'])
{
//If the password for this user is not correct then resond as such
return $app->json(array('Message' => 'Forbidden'), 403);
}
//If everything is fine then the application will carry on as normal
}
});
Full details of implementing HTTP auth in PHP can be found in the PHP manual, this includes how to implement HTTP digest auth.
One of my recent projects required me to build a quick JSON only API to abstract interaction with multiple databases for multiple web applications, as I’d already got some of the logic in Codeigniter I just added Phil Sturgeon’s Codeigniter REST Library. However while this handles all method not found errors when URL routing gets as far as the controller all other errors still appear as HTML, when using curl and attempting to parse as JSON this isn’t helpful.
The Solution
My solution was to extend the core Exceptions class which normally deals with these errors. This is done by creating MY_Exceptions.php in application/core and using something similar to the code below: Read more ▼
This posts was originally written for using pre release versions of php5.4, now PHP5.4 has been release everything should work as before I haven’t tested it. There is probably more choice in ways to install it now.
There was a live demo of this but I couldn’t justify the cost of a whole ec2 instance just for this!
The way I have implemented this may be problematic in Chrome/Safari due to Webkit Bug 23933, ”XMLHttpRequest doesn’t work while submitting a form (useful for progress tracking)” I tested this in firefox (the latest version at the time) and it worked fine. Chrome may or may not work. Let me know how you get on.
Developers who work with PHP applications that upload files commonly struggle with providing user feedback on the upload progress, usually using flash and javascript solutions like uploadify. In PHP 5.4 there is now integrated functionality to allow file upload progress to be passed back to the browser.
In this post I’ll describe the basic operation of this feature and describe a quick example of its use.
How it Works
The upload progress functionality stores the current progress in a session variable which can then be queried as required to give the current progress, it requires the use of PHP native sessions. The $_SESSION key is set by the form name and a prefix defined in php.ini
I’ve been excitedly awaiting some of the new features found in PHP 5.4, in particular array notation and file upload progress monitoring so I decided to try and install PHP 5.4 on Ubuntu. Fortunately there is a repository of prebuilt packages for Ubuntu.
I recommend using a VM so you don’t mess up any stable PHP install.
Update
Since writing this post php 5.4 stable has been released and a more up to date package is available in this ppa: https://launchpad.net/~ondrej/+archive/php5 I haven’t tested this personally but should work as described below.
I’m a regular user of codeigniter-simpletest developed by Eric Barnes however I ran into a number of issues when attempting to run some features under PHP5.3, this was due to using an old version of Simpletest. I have now updated this and had my pull request accepted and merged into the main repo so that it now uses the most recent versions (1.1alpha3).
There is however one important change to note which will stop old tests working, that is the way that test classes define a label, these are optional so this only applies if you use them in your project. The name of the test is now passed through the simpletest constructor otherwise the default is to use the classname of the test.
Before
class test_users_model extends CodeIgniterUnitTestCase
{
public function __construct()
{
parent::__construct();
$this->UnitTestCase('Users Model');
$this->load->model('users/users_model');
}
etc...
After
class test_users_model extends CodeIgniterUnitTestCase
{
public function __construct()
{
parent::__construct('Users Model');
$this->load->model('users/users_model');
}
etc...
This was my first PHPNW conference but after hearing so many good things about the conference in previous years I thought I’d give it a go. In this post I’ll summarise some of my highlights.
Most of my projects at work involve resizing images in PHP applications, usually the result is loaded via AJAX so it needs to be generated as fast as possible for optimum user experience. Recently I discovered the ability to fork processes in PHP, this gives the ability to run multiple functions at the same time. In the example below I’ll demonstrate how parallel processing can be used in PHP to speed the generation of several different sizes of preview images from a large uploaded image.
This code uses the PCNTL extension which was installed as standard on my Ubuntu 11.04 PHP 5.3 install.
This post describes a recent project I completed to display caller id information for incoming calls on my computers. The project uses a BT Caller Display 50 connected via an optoisolating bridge to an arduino with an ethernet shield. When an incoming call is received the telephone number is transmitted via MQTT to a python client on any computer I happen to be using at the time. This project is a great example of someone putting great effort into being lazy, the caller id data is alredy displayed on my phone but the phone generally resides in the next room so this avoids me needing to run for stupid cold callers. Initially I’d wanted to do this project just using the arduino, which may have been possible but using the CD50 makes it a huge amount easier.
Creating sitemaps is a bit of a hassle for any site bigger than a couple of pages, especially where a database is involved. While working on a recent project I created a library for codeigniter which allows the simple creation of sitemaps either by manually adding pages which might be appropriate for a blog, or allowing the library to scan controllers and adding all pages defined by methods. Common search engines can also be notified.
A simple example of it in use is shown below:
//if you're using sparks
$this->load->spark('codeigniter-sitemaps/0.0.1')
$this->load->library('sitemaps');
//assuming a hypothetical posts_model
$posts = $this->posts_model->get_posts();
foreach ($posts AS $post)
{
$item = array(
"loc" => site_url("blog/" . $post->slug),
"lastmod" => date("c", strtotime($post->last_modified)),
"changefreq" => "hourly",
"priority" => "0.8"
);
$this->sitemaps->add_item($item);
}
// file name may change due to compression
$file_name = $this->sitemaps->build("sitemap_blog.xml");
$reponses = $this->sitemaps->ping(site_url($file_name));