Inhoud syndiceren
People blogging about PHP
Bijgewerkt: 11 minuten 32 seconden geleden

Functional PHP talks

do, 13/02/2014 - 11:38
Categorieën: Open Source, PHP Community

PHP 5.6.0alpha2 released

do, 13/02/2014 - 02:00
The PHP development team announces the immediate availability of PHP 5.6.0alpha2. This release adds new features and fixes bugs. All users of PHP are encouraged to test this version carefully, and report any bugs in the bug tracking system. THIS IS A DEVELOPMENT PREVIEW - DO NOT USE IT IN PRODUCTION! PHP 5.6.0alpha2 comes with a number of new features, including: Peer certificates are now verified by default when connecting to SSL/TLS serversAn exponentiation operator has been added: **Output encoding handling has been simplified by using default_charset as the default character encodingFor more information about the new features you can check out the work-in-progress documentation or you can read the full list of changes in the NEWS file contained in the release archive. For source downloads of PHP 5.6.0alpha2 please visit the download page. Windows binaries can be found on Our third alpha should show up on the 27th of February. Thank you for helping us make PHP better.
Categorieën: Open Source, PHP Community

HHVM and Hack – Can We Expect Them to Replace PHP?

wo, 12/02/2014 - 19:00
This entry is part 1 of 1 in the series HHVM and Hack

Facebook started to work on HipHop for PHP in 2008. Their goal was to speed up the PHP execution speed and the first version of the project was composed of the tandem HPHPc/HPHPi. HPHPc is a PHP to C++ transpiler which was used to deploy the code to the production servers while HPHPi was an interpreter used during development and debug stages.

HPHPc did a good job on improving performance but it was not without issues: maintaining both HPHPc and HPHPi in sync proved to be cumbersome plus some differences still existed between the transpiled code vs the interpreted one. That's why back in 2010 Facebook decided to go for another approach and created HHVM – a new virtual machine designed to replace the Zend Engine used by PHP. By the end of 2012 HHVM achieved performance parity with the former HPHPc and soon surpassed it.

HHVM is intended to achieve both parity with the Zend Engine features and best possible performances. Facebook claims a 3x to 10x speed boost and 1/2 memory footprint by switching from PHP+APC to HHVM. Of course this is really application dependent (10x being for the FB code base). This article will not focus on parity nor performances as plenty of resources are already available, check the HHVM blog or google for "hhvm benchmark". To find out more about HipHop and HHVM in general, read the previous SitePoint articles about it.

Instead this article will focus on HACK which is an evolution of the PHP language designed to be safer, to enable better performance and to improve developer efficiency. Note that both HACK and PHP are equally supported by the HHVM. Despite the fact that HACK is in use at Facebook on all the production servers, only little info has leaked for now. In a nutshell, HACK is Facebook's PHP6 – it proposes to fix most of what's wrong with PHP today, while adding some new features like static typing along the way.

Hello HACK

Not all the tools and almost no documentation for HACK have been released as of today. However the latest available HHVM source code already supports HACK. You can install a Vagrant virtual machine to start experimenting with HACK and run the code snippets from this article:

# Vagrant should be installed on your machine
$ git clone
$ cd hhvm-vagrant
$ vagrant up

You are now ready to write your first HACK program:

require "/vagrant/www/xhp/php-lib/init.php";

$hello = "Hello HACK!";

echo <html>

This sample is available in your clone of the vagrant VM (located at www/hello/index.php). You can see the result by pointing your browser to http://localhost:8080/hello/.

A HACK application starts with the <?hh tag located at the very start of your source file – note that there is no closing tag in HACK. This sample is pretty self-explanatory, the only noteworthy point is that is uses XHP, an XML markup language which is also available as a stock PHP extension. More about XHP later in this article.

More interesting HACK goodness will be introduced the following sections.

Constructor argument promotion

Not only is HACK more efficient than stock PHP when it comes to execution speed but it also focuses on improving developer efficiency.

"Constructor argument promotion" is one of the features helping reducing boilerplate code. Indeed, a common pattern when creating a class in PHP is first to declare the properties and then assign all of them straight from constructor arguments. With HACK, adding the visibility as a constructor argument modifier is enough for both declaring the property and initializing it. It makes the code more concise:

class PHPClass {
    public $pub;
    protected $pro;
    private $pri;

    public function __construct($pub, $pro, $pri) {
        $this->pub = $pub;
        $this->pro = $pro;
        $this->pri = $pri;

// object(

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

Categorieën: Open Source, PHP Community

There's no PHP user group here!

wo, 12/02/2014 - 16:00
PHP User Group PHPBenelux
When going to conferences you always hear "join a local user group, and if there's none in your area you're the person who needs to start one". But then what? Where do you get started? How do you organise a PHP user group? Basically, you're left in the dark and you're missing out of all the great stuff everyone else can enjoy.
So how do you get started?
You've attended a conference or visited a remote user group and you're completely pumped up to start a local community in your area. But how do you organise a user group meetup? How do you let people in your area know, you've started something for developers to meet each other, learn from each other and have a good time?
There's no one-size-fits-all solution to these questions though, most of it depends where you're located and what the penetration level is of PHP developers.
The easiest way to let everyone know you're organising a PHP meetup, is using where you can announce your meetups, create a user group profile and more. You can even use meetup as your user group webpage if you don't want to invest in setting up a seperate web page.
Everyone who's already a member of Meetup will receive a mail informing them there's a new meetup in their area: yours!
Meetup costs about $ 2.00 per month

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

Categorieën: Open Source, PHP Community

219 days for one line of code

wo, 12/02/2014 - 07:58

On saturday, 27th of july 2013, one of my TYPO3 core patches got merged: Bug #44118: Debug exception handler sets no exit code .

The patch was written on 19th of december 2012 and consisted of a single line of code. It took 4 revisions, 24 comments and 219 days in total to get merged.

The four patch revisions happened because the TYPO3 core code gets developed further and I had to rebase my patch repeatedly. The 7 characters of code did not change during that time.

It's my fault that there were so many comments necessary; I initially forgot to include step-by-step instructions to reproduce the issue.

And here we see again that it can be really tedious to get patches into the TYPO3 core - even if it's a single line no-brainer, when others do not care.

Categorieën: Open Source, PHP Community

Support for binding Oracle PL/SQL BOOLEAN introduced in PHP OCI8 2.0.7

di, 11/02/2014 - 19:46

I've released PHP OCI8 2.0.7 which has oci_bind_by_name() support for binding PL/SQL's BOOLEAN type to PHP's boolean. The feature is available when PHP OCI8 2.0.7 is linked-with and connects-to Oracle Database 12c. (The necessary Oracle C library support for binding BOOLEAN was introduced in 12c).

Following the existing PHP OCI8 convention, there are two new constants usable with oci_bind_by_name(): SQLT_BOL and OCI_B_BOL. They have identical values. The former mirrors the underlying Oracle library constant's name (yes, it only has one "O"). The latter follows the PHP OCI8 style of having OCI_B_-prefixed names for bind constants. Note the constants can't be used for array binding with oci_bind_array_by_name().

An example usng the new PHP OCI8 2.0.7 feature is:


  Precreate this PL/SQL function:
    create or replace function is_valid(p in number) return boolean as
      if (p < 10) then
        return true;
        return false;
      end if;


$c = oci_connect('hr', 'welcome', 'localhost/pdborcl');

$sql = "begin :r := is_valid(40); end;";
$s = oci_parse($c, $sql);
oci_bind_by_name($s, ':r', $r, -1, SQLT_BOL);  // no need to give length
var_dump($r);                                  // Outputs: bool(false)


Prior to OCI8 2.0.7 you had to write a wrapper PL/SQL block that mapped the PL/SQL true or false values to 1 or 0.

Code without using OCI8 2.0.7:

$sql = "begin if (is_valid(40) = true) then :r := 1; else :r := 0; end if; end;";
$s = oci_parse($c, $sql);
oci_bind_by_name($s, ':r', $r, -1, SQLT_INT);
echo "Result is " . ($r ? "true" : "false") . "\n";  // Outputs: Result is false

The new functionality removes one small pain point and makes your interaction with Oracle Database 12c PL/SQL cleaner and easier.

Categorieën: Open Source, PHP Community

What Application Layer Does A DI Container Belong In?

di, 11/02/2014 - 19:46

James fuller asks:

any thoughts about which layer of the application we should be using a DI container like Aura.Di? Highest layer possible?

Twitter is too constrained and ephemeral for a good response, so I’ll answer that question here.

First, we need to remember that a Dependency Injection container and a Service Locator are indistinguishable from an implementation perspective. (This is a view I accepted only recently.) The difference is in their use: if a container is ever placed into an object so the object can retrieve its own dependencies, that container is being used as a Service Locator. Conversely, if the container stays entirely outside an object so that dependencies are pushed into the object, the container is being used for dependency injection.

If we accept that description, the proper layer for a DI container is outside every other layer in the application (with the possible exception of Factory classes). That means the DI container is part of the bootstrapping code that sets up the application, and not part of anything else.

As an example, we can imagine a web application bootstrap script that looks like this:

// set up the autoloader
include '/path/to/autoload.php';

// create and set up a Container
$container = new Container;

// retrieve a front controller service and run it
$front_controller = $container->get('front_controller');

The purpose of the bootstrap is to create and configure the container with all its services and settings, then pull one object out of the container and invoke it. None of the objects in the system has to know that the container even exists. All of the objects are being created via the container, so in a way the container “contains” the entire object graph.

The part I had the hardest time getting about real dependency injection was this: If you have a class 2 or 3 layers down in the application, and that class needs dependencies, how do they get injected? Don’t you have to pass the dependencies through the intervening layers, and then doesn’t that break a lot of rules, along with violating plain common sense? And what if that class needs access to several different but related objects, but doesn’t necessarily know what they are in advance?

The key for me was realizing that all object creation work happens in the container and not in the classes themselves. This is an alien way of looking at things for most PHP developers, who are more used to Singleton, Registry, and Service Locator, not to mention static calls to ActiveRecord objects. All of these patterns of usage mess with separation of dependencies, but are very common in PHP land, and form the basis of most PHP developers’ understanding of how to work with dependencies.

It took me a year to really “get” the concept of dependency injection, under tutelage from guys like Jeff Moore and Marcus Baker, along with the writings of Misko Hevery. Once I understood it, I wrote the Aura.Di readme file as an introductory document to step readers through the various stages of dependency allocation. Perhaps that document will be helpful to others, even if they don’t choose Aura.Di as a container.


If you work with a legacy application, you already know how hard it is to track dependencies throughout the code. Sometimes the dependencies are global, sometimes they are created inside that class that needs them, and sometimes there is a service locator implementation floating around inside the classes. This makes it frustrating to track down bugs and make wide-ranging changes, and terribly difficult to write tests because everything depends on everything else.

But it doesn’t have to stay that way. My new book, Modernizing Legacy Applications in PHP, gives detailed instructions that will lead you step-by-step from an include-oriented mess of page scripts to a modern architecture using dependency injection techniques.

You can buy the book in early-access mode today, or sign up on the mailing list below to get more information as it becomes available!


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

Categorieën: Open Source, PHP Community

MongoDB and arbitrary key names

di, 11/02/2014 - 11:41
MongoDB and arbitrary key names

I hang out on the MongoDB IRC channel (Freenode/#mongodb) quite a bit, and an often recurring question is inherently abour storing values as keys.

One of the examples is storing timed data points like this:

        person: "derickr",
        steps_made: {
                "20140201": 10800,
                "20140202":  5906,

The sub key under steps_made is the date on which the steps are made, and the value is the amount of steps for that day. A schema like this prevents the same key from being used multiple times—enforcing uniqueness, and it's also possible to add steps from future walks atomically:

<?php $m = new MongoClient;
        [ 'person' => "derickr" ],
        [ '$inc' => [ "steps_made.20140202" => 712 ] ],
        [ 'upsert' => true ]

Because of the upsert option, this update query would even work if there was no document for this person yet in the collection, and it would also work in case a specific date did not have an entry yet.

Although it seems sensible to store the data like this, there are a few problems when storing data like this.

The first problem is this schema makes it impossible to find the step counts for a range of dates—both as a normal query or as with the aggregation framework. This is because you can not query on key names. You would have to request whole documents, and pick out the correct keys in the application.

You can also not easily find which dates had a step count larger than 10000, because you would need to know the key name (date) for the comparison first.

Another problem is indexes. Indexes can only be made on field names. To be able to use an indexed lookup with the above schema, you would need to create an index on steps_made.20140201 and on steps_made.20140202, etc. That is of course not practical.

And lastly, with the schema above you can not create aggregates on years or months as, again, you can only manipulate values with the aggregation framework and not with keys.

So what is the major issue here? The schema uses a value as a key. This is like having an XML schema that looks like this:


This hopefully makes your eyes bleed.

For very similar reasons as you wouldn't do this in XML (validation, XPath queries), you should not do this with MongoDB.

One alternative is to store the data like this:

        person: "derickr",
        steps_made: [
                { date: "20140201", steps: 10800 },
                { date: "20140202", steps:  5906 },

With this schema some of the previous issues go away.

You can create an index on the date field:

<?php $m = new MongoClient;
$m-?>demo->steps->ensureIndex( [ 'date' => 1 ] );

And you can create an aggregation for the average per month:

<?php $m = new MongoClient();
$r = $m-?>demo->steps->aggregate( [
        [ '$match' => [ 'person' => 'derickr' ] ],
        [ '$unwind' => '$steps_made' ],
        [ '$project' => [
                'person' => 1,
                'steps_made'=> '$steps_made.steps',
                'month' => [ '$substr' => [ '$', 0, 6 ] ]
        ] ],
        [ '$group' => [
                '_id' => '$month',
                'avg' => [ '$avg' => '$steps_made' ]
        ] ],
] );
var_dump( $r['result'] );

It is not yet possible to find all the step count for a range of dates, as they are collectively stored in one document and you would always get a whole document back.

You can not easily find which dates had a step count larger than 10000 with a normal query. However you can do that with the aggregation framework, albeit not in a very efficiant way:

<?php $m = new MongoClient();
$r = $m-?>demo->steps->aggregate( [
        [ '$match' => [ 'person' => 'derickr' ] ],
        [ '$unwind' => '$steps_made' ],
        [ '$match' => [ 'steps_made.steps' => [ '$gt' => 10000 ] ] ]
] );
foreach( $r['result'] as $record )
        echo $record['steps_made']['date'], "\n";

An additional problem with storing the

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

Categorieën: Open Source, PHP Community

Learn OOD - to unlearn it again

di, 11/02/2014 - 08:09
One topic we regularly teach in workshops for our customers is object oriented design (ODD), i.e. the art of crafting classes/interfaces in a way that the result is an easy-to-understand, maintainable and flexible code base. With the agile focus on shipping working software, some might consider the skill of OOD less important. One popular argument is that quick reaction to change is more important than designing objects and their interaction carefully. I personally look at it the exact other way around. This blog post summarizes why you need to learn OOD first, in order to avoid it to some degree again.
Categorieën: Open Source, PHP Community

It’s the Booze Talking #6 – APIs Part 1

di, 11/02/2014 - 07:00

Recorded live at Sunshine PHP 2014.

Show Notes:

This episode carries the EXPLICIT tag for language. It is not family friendly. I do apologize if this offends our regular listeners. Feel free to skip this episode and we will return to our normal format soon.

Categorieën: Open Source, PHP Community

Coding Standards: Humans Are Not Computers

ma, 10/02/2014 - 23:51

The Computer in Society - April 1965 ... Feeli...

The Computer in Society - April 1965

This is part rant and part poking fun, but I’ve grown weary with the sight of source code running through phpcs for PSR-2 compliance and finding that it’s riddled with dozens and dozens (and dozens of dozens) of errors and an apparently infinite number of warnings. If I actually fixed all the reported problems, I’d drive myself crazy. I’m not crazy. I’ve avoided insanity because I quit using a coding standard. It’s too much and I freely admit it: I loathe coding standards.

Or do I?

The problem with coding standards is not the notion of following conventions to ensure all programmer can quickly read and understand code (and other good stuff), but that someone created a tool to actually check compliance: PHP_CodeSniffer. This isn’t a complaint about the operation of phpcs, but to complain about the mere fact of its existence. Automated tools catch everything. Every minor deviation, every judgement call about what looks neat, tidy or pretty, and every crucial space character found out of place is tallied into a wall of text in your console demanding that all these crucial lapses are fixed post haste. It doesn’t even have the decency to use smilie faces.

Using the cover of such automated tools, we can make judgement calls about code quality, integrate style checks into Continuous Integration scoring schemes, complain about pull requests and patches, and generally impose a time penalty on writing code. There is a point at which common sense morphs into sheer nitpicking, and an automated tool is the perfect nitpicker.

Get Outta My Way!

For me, a coding standard must have flexibility and it must remain invisible 99% of the time. If the damn thing makes sense, a programmer should have it learned inside of a week. If they have it learned then why would they need constant monitoring? Rather than catering to everyone by dictating everything (and then failing to do even that!), a coding standard should instead state a subset of common sense rules that everyone already uses. In otherwords, it should be almost utterly pointless to an experienced programmer. There’s already a good example of this. PHP-FIG has PSR-1. It’s basic, adheres to standard practice, and you’d have to be doing something completely weird to fail compliance. In other words, it’s perfect.

Beyond PSR-1, we then have PSR-2. Plug PSR-2 into PHP_CodeSniffer and a gateway to Hell will spawn. Most of the standard itself is actually quite logical. In fact, most of it is! The problem is when PSR-2 descends into seemingly trivial matters or omits specific use cases, and then implicitly demands total unquestioning obedience. The trivial matters are those that just never occur to me as being problematic (yes, that would be “opinion”) or which my editor does by default. The omissions are cases where PHP_CodeSniffer feels the need to fill in the blanks, or worse, where an interpretation of the existing wording is in doubt. Both fill my screen and CI reports with utter junk (which is more opinion).

Am I expected to waste my time fixing this junk? I don’t think so. I have better things to do like writing more code, more tests, more documentation, and more rants about the state of security in PHPland. Perhaps eating and sleeping in between ;) .

PSR-2 !== PSR-2

What h

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

Categorieën: Open Source, PHP Community

Managing Gettext Translations on Shared Hosting

ma, 10/02/2014 - 19:00

If you’re working for a big company, chances there are that sooner or later your employers will start to target the global market. With this ambition will come the need to translate the company’s website into one or more languages. Even if you don’t work for a big company, you may have a new service to launch in your native language (assuming you’re not a native English speaker) to target your local market, and in English for the global one. As developers, our role isn’t to translate texts but to prepare the website to support translations. The most popular method to do that in PHP is via Gettext. It’s a great method because it allows to separate translations from the application, enabling the parallelization of the process. The problem with it, is that Apache caches the translations, so unless you can restart the engine, any update to a translation file won’t be seen. This fact is particularly annoying if you work on a shared hosting where you don’t have administrator permissions. In this article, I’ll describe this issue in detail and explain the solution I found to avoid it.

Note: If you aren’t familiar with the concepts of I18N, translations, and Gettext, I strongly encourage you to read this series before exploring this article further. It will provide you with more details than the brief overview you’ll find here, and will help you have a better comprehension of these topics.

Setting up the Environment

There a lot of ways to use translations in PHP. The simplest one I can recall is to have an associative array containing all the translated strings and then use the keys to retrieve the right. As you may guess, this solution doesn’t scale well and should be avoided unless you’re working on a very very small project (perhaps something not longer than 5 lines of code). For serious translations we can use Gettext. This approach enables us to have different files for every targeted language which helps in maintaining separation between the business logic, the presentation layer, and the translations (which we can see as an add-on of the presentation layer). With Gettext, we can parallelize the process because while we’re working on some features of the website, translators can still work on translations using software like Poedit.

Translations should be stored in a path having a fixed structure. First of all, we’ll have a root folder named to your taste (for example “languages”). Inside it, we have to create a folder for every targeted language whose name must comply to the ISO 3166 standard. So, valid names for an Italian translation can be “it_IT” (Italian of Italy), “it_CH” (Italian of Switzerland), “en_US” (English of USA), and so on. Within the folder having the language code, we must have a folder named “LC_MESSAGES” where, finally, we’ll store the translation files.

Poedit, analyzing the source of the website, extracts the strings to translate based on one or more patterns we set in the software. It saves the strings in a single file having .po (Portable Object) as its extention that this software (or one equivalent) will compile into binary .mo file. The latter is the format of interest for us and for the PHP’s gettext() function. The .mo file is the one we must place inside the “LC_MESSAGES” directory we created earlier.

A sample code that uses gettext() is the following (the code is commented to give you a quick grasp of what it does):

   // The name of the root folder containing the translation files
   $translationsPath = 'languages';
       // The language into which to translate
       $language = 'it_IT';
   // The name of the translation file (referred as domain in gettext)
   $domain = 'audero';

   // Instructs which language will be used for this session
   putenv("LANG=" . $language); 
       setlocale(LC_ALL, $language);

   // Sets the path for the current domain
   bindtextdomain($domain, $translationsPath);
   // Specifies the character encoding
   bind_textdomain_codeset($domain, 'UTF-8');

   // Choose domain

   // Call the gettext() function (it has an alias called _())
   echo gettext("HELLO_WORLD"); // equivalent to echo _("HELLO_WORLD");

Once you save the previous code in a page and load it in your browser, if gettext() is able to find the translation file, you’ll see the translations you made on the screen.

So far, so good. The bad news is that once a translation is loaded, Apache caches it. Therefore, unless we can restart the engine, any update to a tr

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

Categorieën: Open Source, PHP Community

Integrate Social Sign On in your PHP apps using HybridAuth

ma, 10/02/2014 - 18:30
Integrating social sign-ons in a web application can become a tedious task because you need to take care of different endpoints, credentials and finally manage the oauth dance to get the access token. However, using HybridAuth package, this task can be easy as pie Let’s have a look In this example I will show you... Read More in Integrate Social Sign On in your PHP apps using HybridAuth
Categorieën: Open Source, PHP Community

PhpStorm – Top Productivity Hacks and Shortcuts

zo, 09/02/2014 - 21:00

We all have our favorite IDEs/editors when coding. Mine is PhpStorm, and it took a while to master all its shortcuts and establish a rapid workflow. In this article, I’ll share some keyboard shortcuts and tips with you which you should make part of your regular routine if you, too, do your work in this IDE. This article was partially inspired by this Reddit thread, and will be mentioning and demonstrating some of the shortcuts found there as well.

Note that as I’m doing my development on Linux in a vagrant box hosted on Windows, I’ll be using CTRL instead of CMD. If you’re on OS X, just imagine it says CMD.

Keyboard shortcuts and hacks

PhpStorm’s high configurability (it’s almost an “Android” of the PHP IDE world) lets you fine tune it to infinity – you can make it into a tool so personal, it might seem like a different IDE to anyone opening your settings. Let’s see some shortcuts and hacks we can take advantage of:

  • CTRL + ALT + L, one of my most used keyboard combos, will immediately format your code according to the preferred style guidelines:

    What’s more, as you can see by the popup that appears in the animation above, you can choose to reformat your entire project. If you use this excessively and don’t often work on other people’s projects, you take it up another notch – bind a macro to the CTRL+S shortcut, and make PhpStorm automatically reformat your code on every manual save. Note, however, that if you’re working on a project with someone else, this might cause refactors in various files far too often, and pollute your version control system with changes that aren’t changes at all. If you’re on Linux, your CTRL+ALT+L shortcut might already be bound to “Lock Screen”, and you’ll need to unbind it from the system, or change it in PhpStorm’s settings.

  • Pressing CTRL+SHIFT+Backspace, or the “Forward” and “Back” buttons on your mouse if you have them, will walk you through your previous edit locations. This is very useful when dealing with large files and having to reference another part only to come back to the original to continue the work:

  • Holding down CTRL when hovering over variables or methods will give you their full names or locations of declaration, while CTRL+Clicking on a variable or method, or pressing CTRL+B when on a method’s call or on a variable will take you directly to where it’s defined:

  • CTRL+Space will summon a code hinting dialog, if you accidentally closed it or for some reason it didn’t open:

  • When PhpStorm detects some problems, it will underline the problematic area and summon a lightblub on top of it when you hover your mouse or keyboard cursor in that area. Clicking this light bulb or pressing ALT+Enter will suggest solutions – in any language. This can range from turning off error reports for suppressed notices (something I recommend against), to merging CSS rules:

  • CTRL+N and CTRL+SHIFT+N will let you instantly move to any part of any class or file in your entire project:

    The search is fuzzy, and also supports line numbers – you can use abbreviations followed by :XX where XX is the line number:

  • PhpStorm remembers multiple clipboard contents – you can press CTRL+SHIFT+V to summon a popup which lets you paste clipboard content that’s less recent than the latest.

  • If you’re in love with Sublime’s ability to search for commands of the IDE itself, you can do that too. CTRL+SHIFT+A will spawn a command search popup. Forgot how the code reformat shortcut goes? Just CTRL+SHIFT+A and type “refor..”:

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

Categorieën: Open Source, PHP Community

Sunshine PHP 2014

za, 08/02/2014 - 18:05

Due to uncertainties in my work schedule, I decided this year not to submit to the Sunshine PHP 2014 conference. However, the schedule turned out such that I was able to attend the conference. Many thanks to my awesome employer Blopboard for providing the time and funding to make this possible.

I was a speaker at the inaugural Sunshine PHP conference in 2013 and enjoyed that experience, but being able to just be an attendee this year was a nice change of pace. I’ve enjoyed the awesome content presented by excellent speakers.

With this year’s Sunshine PHP came a new member of the elePHPant family: Sonny, the yellow elePHPant. The process of obtaining your very own Sonny was a rather novel idea thought up by the hosts of Sunshine PHP. Attendees were given a bingo sheet where each space was branded for a sponsor and would visit the sponsor’s booth to get that space stamped. Once all spaces were stamped, you could turn in the bingo sheet to get Sonny.

In going through this process, I spoke with some very friendly guys at AppDynamics. I was able to learn more about their product, which is an alternative to the New Relic service I currently use at work for monitoring the performance of our product. I noted that AppDynamics isn’t currently listed in the Heroku add-on marketplace, but they clarified for me that it can still be installed on Heroku and pointed out related documentation.

The interaction was great and I’ll certainly be checking out the product further, but this quest to get Sonny is what instigated that conversation, which I think is awesome. Many thanks to Zend for sponsoring this fun activity within the conference.

Thanks to everyone who made Sunshine PHP a spectacular event to attend. I hope to see you again next year.

Sonny the yellow elePHPant


Categorieën: Open Source, PHP Community

SunshinePHP: Application Logic Security Slides

vr, 07/02/2014 - 23:10
My slides from the "Application Logic Security" talk at SunshinePHP are now available here. If you've attended talk, I'd love to hear your feedback via Joind.In.
Categorieën: Open Source, PHP Community

The Pros and Cons of Zend Certification

vr, 07/02/2014 - 19:00

As a PHP developer, you may have been asking yourself how to improve your skills, gain reputation or become more professional in your work. One of the ways of doing so is to get through a certification programme. The only one that covers PHP itself (not a particular framework or software solution) is being delivered by the Zend company. In the remainder of the article I will focus on this particular certificate and describe its advantages and disadvantages. At the end I will also mention some other certification programs that may be valuable to a PHP developer.

Please note that I’m not affiliated in any way with the companies that offer the certification programs described in the article.

Zend certification – general info

The Zend company offers the Zend Certified PHP Engineer certification programme which covers different areas of developing applications in PHP 5.5. The topics that you have to learn for the exam are grouped in several categories like PHP Basics, Object Oriented Programming, Security or Arrays. The company offers a course that prepares for the exam but it’s not mandatory. The exam itself may be taken in one of Pearson VUE Testing Centers which are available all over the world, so it probably won’t be difficult to find a testing center near your location. The cost of the exam is $195.

Possible benefits

1. A way of confirming your skills
Of course the basic goal of getting certified is to get a formal confirmation of your programming skills. After passing the exam you can describe yourself as a Zend Certified Engineer (e.g. in your CV) and you will be listed in the directory containing all of those who passed.

In my opinion, getting certified may be especially important if you’re an intermediate PHP developer and you want to distinguish yourself from beginners. As the exam itself isn’t simple, I think it will probably be too difficult for those who are just starting out. The exam covers different areas of PHP in a detailed way which probably won’t be necessary and will be too complex for newbies. On the other hand, it’s worth keeping in mind that advanced PHP programmers can prove their skills just by referring to their professional experience. The applications they have worked on in the past, the code they have written or their commitment to open source projects may be a more valuable proof of their skills than the certificate.

2. A way to review and extend your knowledge
If you plan to take the exam, you will certainly have to prepare for it. As it covers all of the PHP basic functionalities, the preparation for the exam may be a good way of learning different aspects of PHP or reviewing your knowledge.

When you started writing PHP applications, you probably went through some basic tutorials or a book or two. Then, as you were becoming more advanced, you read more on the topics that you needed to learn about. You searched the web looking for solutions to specific problems, you read different books and articles concerning the subjects you were working on. But have you done a course that covers all of the PHP concepts in a thorough way, from beginning to end? Probably not. That’s why the preparation for the PHP certification exam may be valuable. It may be an opportunity to review the knowledge in the areas that you are already familiar with and learn something new about the other topics you may have skipped.

The Zend certificate covers a lot of ground, from basic concepts like the syntax, operators or language constructs, to all of the different features of the PHP like working with files, string and array manipulation, handling sessions, cookies and form data etc. During the exam you may be also asked about databases and SQL, basics of HTTP requests or different data types (JSON, XML etc.). So if you want to get the certificate you will have to get familiar with all aspects of the language, not only the ones that are, for example, needed in your work right now. As a result, you may gain a wider perspective on PHP itself and find some tools or solutions that you didn’t know of before. You may also discover some areas that you are weak in and get motivated to work on them.

The drawbacks

1. The construction of some of the exam questions
The exam consists of about 70 questions. You can find sample questions on the Zend website to see how they are built. Some of them just ask you What will the following code produce? and contain a code sample that you

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

Categorieën: Open Source, PHP Community

Mockery 0.9.0 Has Landed…Mostly In One Piece!

do, 06/02/2014 - 22:28

The Enterprise ' s saucer section crash landing

The Enterprise ' s saucer section crash landing (Photo credit: Wikipedia)

I’m very happy to announce the release of Mockery 0.9.0.

Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its core goal is to offer a test double framework with a succint API capable of clearly defining all possible object operations and interactions using a human readable Domain Specific Language (DSL). Designed as a drop in alternative to PHPUnit’s phpunit-mock-objects library, Mockery is easy to integrate with PHPUnit and can operate alongside phpunit-mock-objects without the World ending.

According to the number crunching machines over at VersionEye, Mockery is the 7th most referenced Composer package for PHP with 1,051 packages currently referencing Mockery as a development dependency. That is a great achievement and I appreciate the efforts of everyone who has taken the time to send in issues and pull requests.

Thanks to the efforts of Dave Marshall (@davedevelopment), who has taken point on Mockery for most of 2013, the new release improves stability, performance and compatibility with HHVM. I was going to trawl through the commits to write a summary of changes, but Dave was kind enough to do that for me too so here are the highlights. The new 0.9.0 release is now available on and through the PEAR channel.

Mocking Protected Methods

Contentious point for purists, but Mockery now allows you to mock protected methods, but it’s specifically opt-in. Its main use case will be shorthand for making fake derivatives of abstract classes.


require "vendor/autoload.php";

abstract class Foo
 public function bar()
 $res = $this->doBar();
 return $res * 2;

 abstract protected function doBar();

$foo = Mockery::mock("Foo")->makePartial()


echo $foo->bar(); // 256
Generator Rewrite

The code generation has been completely rewritten, it’s a little cleaner and has more unit tests. This new generator is now wrapped with a caching layer by default. This means that Mockery wont generate a new mock class if it’s already generated a suitable class.


$fooMock1 = Mockery::mock("Foo"); // generates a mock class deriving from Foo
$fooMock2 = Mockery::mock("Foo"); // re-uses the same mock class

$partialFoo = Mockery::mock("Foo[bar]"); // can't reuse class, so generates new

This brings significant performance boosts on larger suites, particularly with memory consumption. It’s not all that important to some, but I like a fast feedback loop and it will definitely help some people running their suites on travis with xdebug for coverage.

laravel/framework with Mockery 0.8.0 and Zend PHP 5.5.6
Time: 3.9 seconds, Memory: 276.50Mb

laravel/framework with Mockery 0.9.0 and Zend PHP 5.5.6
Time: 1.61 seconds, Memory: 66.50Mb

laravel/framework with Mockery 0.8.0 and Zend PHP 5.5.6 w/xdebug
Time: 5.96 seconds, Memory: 334.25Mb

laravel/framework with Mockery 0.9.0 and Zend PHP 5.5.6 w/xdebug
Time: 3.38 seconds, Memory: 74.00Mb

laravel/framework with Mockery 0.8.0 and HHVM
Time: 42.91 seconds, Memory: 388.57Mb

laravel/framework with

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

Categorieën: Open Source, PHP Community

PHP 5.4.25 Released!

do, 06/02/2014 - 02:00
The PHP development team announces the immediate availability of PHP 5.4.25. 5 bugs were fixed in this release. All PHP 5.4 users are encouraged to upgrade to this version. For source downloads of PHP 5.4.25 please visit our downloads page, Windows binaries can be found on The list of changes is recorded in the ChangeLog.
Categorieën: Open Source, PHP Community

Cursors in MySQL Stored Procedures

wo, 05/02/2014 - 19:00

After my previous article on Stored Procedures was published on SitePoint, I received quite a number of comments. One of them suggested further elaboration on CURSOR, an important feature in Stored Procedures.

As cursors are a part of a Stored Procedure, we will elaborate a bit more on SP in this article as well. In particular, we will see how to return a dataset from an SP.

What is a CURSOR?

A cursor can’t be used by itself in MySQL. It is an essential component in stored procedures. I would be inclined to treat a cursor as a “pointer” in C/C++, or an iterator in PHP’s foreach statement.

With cursors, we can traverse a dataset and manipulate each record to accomplish certain tasks. When such an operation on a record can also be done in the PHP layer, it saves data transfer amounts as we can just return the processed aggregation/statistical result back to the PHP layer (thus eliminating the selectforeach – manipulation process at the client side).

Since a cursor is implemented in a stored procedure, it has all the benefits (and limitations) of an SP (access control, pre-compiled, hard to debug, etc).

The official documentation on cursors is located here. It contains only four commands that are related to cursor declaration, opening, closing, and fetching. As mentioned above, we will also touch on some other stored procedure statements. Let’s get started.

A real world question

My personal website has a page showing the scores of my favorite NBA team: LA Lakers. The table structure behind it is straightforward:

Fig 1. The Lakers matches status table structure

I have been updating this table since 2008. Some of the latest records showing Lakers’ 2013-14 season are shown below:

Fig 2. The Lakers matches status table data (partial) for 2013-2014 season

(I am using MySQL Workbench as the GUI tool to manage my MySQL databases. You can use your favorite tool.)

Well, I have to admit Lakers are not playing very well these days. 6 consecutive losses up to Jan 15th. I get this “6 consecutive losses” by manually counting from the last played match all the way up (towards earlier games) and see how long an “L” (meaning a loss) in winlose column can appear. This is certainly doable but if the requirement becomes more complicated in a larger table, it takes more time and is more error prone.

Can we do this with a single SQL statement? I am not an SQL expert and I haven’t been able to figure out how to achieve the desired result (“6 consecutive losses”) from one SQL statement. The input of gurus will be highly appreciated – leave it in the comments below.

Can we do this in PHP? Yes, of course. We can retrieve the game data (particularly, the winlose column) for current season and do a traverse on the records to calculate the current longest win/lose streak. But to do that, we will have to grab all data for that year and most of the data will be wasted (as it is not likely for a team to have a win/lose streak for more than 20+ games in a 82-game regular season). However, we don’t know how many records should be retrieved into PHP to determine the streak, so this waste is a must. And finally, if the current win/lose streak is the only thing we want to know from that table, why pull all the raw data?

Can we do this via other means? Yes, it is possible. For example, we can create a redundant table specifically designed to store the current win/lose streak. Every insertion of the record will update that table too. But this is way too cumbersome and too error prone.

So, what is a better way to achieve this result?

Using Cursor in a Stored Procedure

As the name of this article suggests, we will see a better alternative (in my view) to solve this problem: using cursor in a Stored Procedure.

Let’s create the first SP in MySQL Workbench as follows:



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

Categorieën: Open Source, PHP Community