SitePoint PHPSpeeding up Existing Apps with a Redis Cache (27.7.2015, 16:00 UTC)

We’ve gone through the basics of Redis in PHP before, but it’s time to cover a real life use case. In this tutorial, we’ll add it to an already deployed application to give the app the appearance of speed.

Redis Logo

You can easily follow along by cloning the 0.6 release of the app.

The Problem

Before applying a solution, we need to have a clear definition of the problem.

The application in question, when executing a query, runs off to Diffbot’s API and makes it query the dataset. The subset is then returned and displayed. This can take up to 5 or so seconds, depending on the busyness of Diffbot’s servers. While the situation will undoubtedly improve as they expand their computational capacity, it would be nice if a query executed once were remembered and reused for 24 hours, seeing as the collection is only refreshed that often anyway.

“But what good is caching a single query?” you might wonder. It’s not like most people will search for one and the same thing often.

Well… as a matter of fact, not only has research shown that they will often search for one and the same thing (React is trending? Sudden influx of “react” queries), they will also very reliably search for prolific authors (or themselves). Considering the fact that implementing this cache costs us literally nothing (and actually reduces costs by reducing strain on the servers), adding it in is an easy win, even if it weren’t used as often as one would hope. There is no reason not to add it - it can only benefit us.

With the problem clearly defined, let’s handle the prerequisites.

Continue reading %Speeding up Existing Apps with a Redis Cache%

PHP ClassesHow to Render 3D Surfaces in PHP using 2D Contour Plots (27.7.2015, 07:32 UTC)
By Dan Thanh
Contour plots are graphics that render lines that connect points in a geographic region that have the same value, for instance points in a terrain with the same altitude. They are useful for instance to represent 3D features of a terrain in a 2D image.

Read this article to learn more about contour plots and how to render them using the PHP Contour Plot package.
Michelangelo van DamSpeeding up database calls with PDO and iterators (26.7.2015, 14:14 UTC)
Image source:
When you review lots of code, you often wonder why things were written the way they were. Especially when making expensive calls to a database, I still see things that could and should be improved.

No framework development

When working with a framework, mostly these database calls are optimized for the developer and abstract the complex logic to improve and optimize the retrieval and usage of data. But then developers need to build something without a framework and end up using the basics of PHP in a sub-optimal way.

$pdo = new \PDO(

$sql = 'SELECT * FROM `gen_contact` ORDER BY `contact_modified` DESC';

$stmt = $pdo->prepare($sql);
$data = $stmt->fetchAll(\PDO::FETCH_OBJ);

echo 'Getting the contacts that changed the last 3 months' . PHP_EOL;
foreach ($data as $row) {
$dt = new \DateTime('2015-04-01 00:00:00');
if ($dt->format('Y-m-d') . '00:00:00' < $row->contact_modified) {
echo sprintf(
'%s (%s)| modified %s',
) . PHP_EOL;
Above example code is a most common way to retrieve data. At first sight, this code is clean and looks good, but looking more closely you will discover a couple of points to improve.

  • Above code is not reusable, so whenever you need a similar functionality you're stuck with duplicating existing code.
  • Even though you're fetching an object with $stmt->fetchAll(\PDO::FETCH_OBJ); you still face the issue you're using an array of objects which will consume too much memory when fetching lots of data.
  • Filtering is done within the routine, which also means that if you have other filtering conditions you need to modify existing logic, making it hard for maintenance and expanding functionality.


Most of the modern frameworks are using Iterators for their data retrieval, because they're fast and reusable. But also they allow other Iterators to filter and modify the retrieved results. Building an application without a framework still gives you the option to use Iterators as they're part of PHP since Version 5.0.0 Beta 2.

So lets assume you continue to use PDO for your data retrieval, we can choose between two options:
  1. Use PDOStatement::fetchAll() to retrieve all data in a single go
  2. Use PDOSTatement::fetch() to retrieve a single row per iteration

Truncated by Planet PHP, read more at the original (another 8896 bytes)

blog.phpdevCustom Callbacks with Invoke (26.7.2015, 12:59 UTC)

In putting the Invoke library to use I noticed something. While I could tell it to check for groups and permissions on the current user and limit HTTP methods on the request, there were more complex things I needed to check that weren’t part of these defaults. Now, I could just extend invoke to include match types for everything I needed (injecting a custom match class based on my needs) but I wanted something a bit more generic that I could use to call my own logic and return the pass/fail result.

So, I added in the “object.callback” match type that allows you to call a static method in your own code and perform the evaluation yourself. Here’s how it works. Say you have this configuration in your routes.yml file:

  protected: on
  callback: \App\MyUser::test

This tells Invoke that when the user requests the /foo URL, the protection should kick in. It then goes into the checks portion of the process. This sees the special callback option and looks the class and method to call. In this case, we’ve told it to try calling the test method \App\MyUser. This class needs to be autoloadable so that Invoke can directly call it and its static method. Yep, that’s right – it needs to be a static method but you’ll be provided with everything about the request in the incoming $data variable. Here’s what the method should look like:

public static function test(\Psecio\Invoke\Data $data)
  /* perform your evaluation here and return a boolean */

In the $data variable there, you’ll have access to the context of the application via some object properties:

  • user: The current InvokeUser instance (ideally where your user lies too)
  • resource: The resource that was requested (includes access to the requested URI)
  • route: This is the route match from Invoke’s configuration the current request matches. This contains the route regex match, the configuration options and any additional parameters passed along

For example, say you needed to get the parameters from the request to do further evaluation. You could fetch them through $data->resource->getParams() and get the associative array back.

Adding these callbacks makes the Invoke system a lot more flexible and allows you to create those custom match types without having to have whole other classes just to perform your checks.

SitePoint PHPConsole Wars – PHP CLI Libraries (25.7.2015, 16:00 UTC)

I have always been a big fan of console commands and I try to provide a command line interface (CLI) as much as possible in most of my PHP projects. In this article, I’ll briefly compare three PHP console command libraries: The Symfony console component (symfony/Console) The Hoa console (hoa/console) The Webmozart console (webmozart/console) Origin […]

Continue reading %Console Wars – PHP CLI Libraries%

Official Blog of the PEAR Group/PEAR PresidentPEAR 1.10.0dev1 brings PHP 7 compatibility! (25.7.2015, 13:36 UTC)

We’ve released PEAR installer version 1.10.0dev1, which brings support for PHP 7 while dropping support for PHP 4 – 5.3.

See the announcement post @ for more information.

Christian WeiskePEAR 1.10.0dev1 brings PHP 7 compatibility! (25.7.2015, 11:50 UTC)

The new PEAR installer release adds PHP 7 support while dropping support for PHP 4 - 5.3. It also fixes a nasty SSL issue that made it hard to use on PHP 5.6. With the update, strict warnings about static calls to a non-static PEAR::isError() are a thing of the past.

I've just published the first preview version: PEAR 1.10.0dev1.

You can upgrade your existing PEAR version with the following command:

$ pear upgrade PEAR-1.10.0dev1

Pre-release versions of go-pear.phar and install-pear-nozlib.phar can be temporarily be found at

Please report any bugs you find on the PEAR bug tracker or on the pear-dev mailing list.

I'm looking for a new job. If you can recommend a company in Leipzig/Germany that's looking for a PHP developer, please drop me a mail.

Simon HolywellSQL style guide (24.7.2015, 11:37 UTC)

When you’re working in a team you need ways to easily share and denote good style and taste. This is true of your primary programming language with PEP8 for Python and PSRs 1 & 2 for PHP being well known. There is probably even a style guide for HTML and CSS set out at your company. So why should SQL miss out on the party?

I have written a style guide for SQL to promote a consistent code style ensuring legible and maintainable projects -

SELECT a.title, a.release_date
  FROM albums AS a
 WHERE a.title = 'Charcoal Lane'
    OR a.title = 'The New Danger';

There are so many variant SQL styles that projects and people use which can make code difficult to easily read. Looking over various questions on Stackoverflow (on of which was mine!) I noticed that there were elements of good style that were shared by most examples.

I figured it was time that SQL had a concise and easy to read style guide that could easily be adopted and/or modified for bespoke requirements.

It is trivial to apply this style to your projects now or going forward. In the case of PHP you could have some code like the following.

$year = filter_input(INPUT_GET, 'year', FILTER_SANITIZE_NUMBER_INT);
$db = new PDO(
$statement = $db->prepare("
SELECT r.last_name,
       (SELECT MAX(YEAR(championship_date))
          FROM champions AS c
         WHERE c.last_name = r.last_name
           AND c.confirmed = 'Y') AS last_championship_year
  FROM riders AS r
 WHERE r.last_name IN
       (SELECT c.last_name
          FROM champions AS c
         WHERE YEAR(championship_date) > :year
           AND c.confirmed = 'Y');
$statement->bindParam(':year', $year, PDO::PARAM_INT)
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

To produce the guide I settled upon using GitHub Pages, Jekyll and Markdown sources. This means it is very easy to make forks, open issues and pull requests as GitHub Pages will handle the hosting and site build process. It is released under the Creative Commons Attribution-ShareAlike 4.0 International License.

The style in this guide is explicitly designed to be compatible with Joe Celko’s book SQL Programming Style so that teams who have already read that book will find the guide easy to adopt.

To read the guide you can simply visit and to access the sources you can find the repository on GitHub.

If you like the guide please consider sharing it with your team and via twitter - thanks!

Lorna MitchellTest Your PHP Application on PHP 7 (24.7.2015, 10:52 UTC)

PHP 7 is coming, which is nice, but what does it mean for the majority of PHP developers? PHP as a community is notoriously slow in adoption, some of us are still waiting for 2012's new shiny to be available as standard on our hosting platforms. However with the performance benefits and a few really nice new features, PHP 7 is well worth everyone's attention, and it's actually quite easy to get started so here's my quick howto.

Get A PHP 7 Platform

These examples use Rasmus' php7dev box because it's self-contained so it won't affect any other part of your setup, and because it's super-simple to get started with on any platform. It's a vagrant box running Debian 8 and with a really easy way of switching PHP versions, including 7. Multiple PHP versions is super handy because then you can very easily check if your PHP 7 bug really is a PHP 7 bug or if it was there on PHP 5.6 as well.

To get a new project set up you need to make the files available in the PHP 7 VM, and set up an nginx server block (equivalent of a virtual host) to point to it. If your project needs storage behind it, you can either connect to those on your host machine, or the VM has MySQL and PostgreSQL already installed.

Mount Your Project As A Shared Folder

Do this step before booting the virtual machine (or just vagrant halt). Add a line to Vagrantfile to tell the VM to share another folder:

    config.vm.synced_folder "/home/lorna/projects/joindin", "/vagrant/joindin"

I added mine immediately before the end at the bottom of the file - the first directory path is where it is on my laptop, and the second is where it will be in the VM. Now when you vagrant up and SSH in (vagrant ssh from the same directory as the Vagrantfile), you should see your directory is there with the files present.

Configure Nginx

While I mostly use Apache with mod_php, this box defaults to using nginx and it's easy to set up even if you haven't used it before. All we need to do is create a new file in /etc/nginx/conf.d, and add something like (there's a lot of this, I obviously copy/pasted the starting point from somewhere but I'm pretty sure it has everything that most applications need so try it):

server {
    listen       80;
    server_name  api.joindin.php7;
    root   /vagrant/joindin/joindin-api/src/public;
    index  index.php;
    access_log  /var/log/nginx/default-access.log  main;
    error_log   /var/log/nginx/default-error.log;

    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /var/www/default;

    location / {
        try_files $uri $uri/ @rewrite;
    location @rewrite {
        rewrite ^(.*)$ /index.php;

    location ~ \.php {
        include                  fastcgi_params;
        fastcgi_keep_conn on;
        fastcgi_index            index.php;
        fastcgi_split_path_info  ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/var/run/php-fpm.sock;

Edit your server_name and root settings as appropriate, then restart nginx with:

sudo service nginx restart

At this point, the VM is ready but our host machine (in this case my laptop) doesn't know where to send the traffic.

Set Up Your Host File

The VM will by default have an IP address of and hopefully you know where your hosts file is. I'm on Ubuntu so mine is /etc/hosts and I just need to add one line to it: api.joindin.php7

You should now be able to hit your chosen hostname from your browser and see your PHP application working (or not). Error logs are in /var/log/nginx, and as I say, it's worth switching back to PHP5.6 (by running newphp 56 - then you want newphp 7 to switch back later) to check if the problem is actually PHP 7 or if you set something else up wrong.

If you have test suites, please run them, and put your application through its paces. Any bugs you find, try to narrow down the replication case and report them to the appropriate place - this might be your team, but could just as easily be a library, a framework, or PHP itself. The only way to get PHP and its ecosystem as good as it can be before it goes stable is for all of us to do with it before release all the things we'll want to do after!

Getting Going With PHP 7

Hopefully this gave you a quick-start on a very easy pla

Truncated by Planet PHP, read more at the original (another 1054 bytes)

Remi ColletNew "remi-php70" repository (24.7.2015, 05:52 UTC)

I've just open the remi-php70 repository for Fedora ≥ 21 and Enterprise Linux ≥ 6.

Current version is PHP 7.0.0beta2 with about 25 extensions which are already compatible.

emblem-important-4-24.pngThis repository provides developement versions which are not suitable for production usage.

The repository configuration is provided by the latest version of the remi-release package:

  • remi-release-21-2.fc21.remi
  • remi-release-22-2.fc22.remi
  • remi-release-6.5-2.el6.remi
  • remi-release-7.1-2.el7.remi

emblem-notice-24.pngAs for other remi's repositories, it is disabled by default, so the update is an administrator choice.

E.g. to update the PHP system version:

yum --enablerepo=remi update remi-release
yum --enablerepo=remi-php70 update php\*

emblem-important-2-24.pngAs lot of extensions are not yet available, the update may fail, in this case you have to remove not yet compatible extensions, or wait for their update.

I don't plan to open this repository for EL-5 which is near to end of life.

PHP 7.0 as Software Collection stay in "remi-test" (before the switch to "remi") as there is no conflicts with the base packages.

LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP