Category Archives: PHP

PHP 5.4 compatibility checks using PHP_CodeSniffer

Update (27 Nov) : Support for PHP 5.5alpha is included.

For those of you who are new to this concept, check my blog post from a while ago. It will explain the basic concept of using PHP_CodeSniffer to automate compatibility checks. But don’t use the download links, because they point to the old (PHP 5.3) version !

What’s new ?

Quite a few things have changed in this new release :

  • There’s no version specific release anymore. The previous codesniffer standard was called PHP53Compatibility, but it seemed quite stupid to make a new standard for every PHP version out there, especially since that would keep certain people from upgrading to the latest major PHP version. So the new PHPCompatibility standard works for 5.0 – 5.4
  • But since some people simply can’t upgrade to the latest version, I added version information to all the checks. For example : the deprecated  function checker will now tell you that session_register() is deprecated since PHP 5.3 and removed since PHP 5.4 – if you’re running 5.2 and want to move to 5.3, at least you know right away that you’ll have to fix that problem, because otherwise you can’t ever upgrade to 5.4. This version check is available on deprecated/removed function, deprecated/removed php.ini directives and deprecated/removed extensions.
  • Default timezone check has been added : since PHP 5.4, you need to have a default timezone set or PHP will complain. This is ofcourse only useful if you run the tests on a system with identical settings as your production environment.
  • A check for the removed functionality on break and continue was added. (Using a variable or function call as a parameter on break and continue is no longer allowed.)
  • 2 algorithms were removed in the hash extension, so there’s a check for that as well

Where to get it

2 options :

  • Using git : run this in your PHP_CodeSniffer/Standards directory :
    ~ > git clone git://github.com/wimg/PHPCompat_CodeSniffer.git PHPCompatibility
  • Downloading a zip : download here and unzip the file in PHP_CodeSniffer/Standards/PHPCompatibility

How to run it

Start PHP_CodeSniffer like this :
phpcs --standard=PHPCompatibility

Enjoy !

As always, any feedback (or patches on Github) welcome !

Zendcon, ACL talk, conferences and other stuff

ACL talk (Zend Webinar)
Remember I promised to post the code of my ACL Webinar somewhere in August ? That didn’t really happen, partly because of a lack of time, partly because after my initial hard drive crash (which made me lose my slides and code), I had another crash in August and then my boot SSD drive crashed in September. Dell was kind enough to replace the power supply, motherboard and 1 disk, but my data was lost (unless I pay over 500EUR to have it recovered, which is a bit too pricy for my liking).
So all those setbacks caused a lot of delay on my promise. Nevertheless, I presented the talk again at the Zendcon Unconference, also mentioning the plans I have in store for version 2. But ofcourse, I’ll have to release version 1 first. Currently I’m using DHTMLX Treeview for the backend treeview interface, but I’m not allowed to redistribute the commercial version I bought. So as soon as I can replace the backend treeview interface with a free one, I’ll release the entire code, including instructions on how to set it up. And since development for version 2 is already underway, I want to make sure I make a good choice there 😉

Zendcon 2011
Last week I spent a few days at Zendcon in Santa Clara, CA. I saw lots of interesting session there and presented 2 sessions during the Zendcon Unconference (community style version of the main conference) :

  • Creating dynamic ACLs in Zend Framework : the Zend Webinar I presented in August
  • Scaling dynamic sites like static sites : a first glimpse on a new Nginx module we’re building to make dynamic sites behave more like static sites in terms of scalability, without losing their dynamic nature

I received some encouraging comments, so I’m looking forward to presenting more on these topics in the next few months. The Nginx talk should also have some real-world benchmarks the next time I present it.
If you saw either one of my talks, please rate it at Joind.in

Next talks
I’m scheduled to talk at 2 more conferences this year :

  • T-Dose (Technical Dutch Open Source Event) in Eindhoven, The Netherlands on Nov 5-6, 2011 :
    • Nov 5 @ 11:00 : Caching and Tuning fun for high scalability – the talk I presented at phpBenelux, Dyncon and FrOSCon, this time in a condensed 50 minute version – this talk discusses the techniques you can use to keep your site running when it goes from 5 to 5 million visitors/day
    • Nov 6 @ 12:00 : Beyond the code : it’s not (just) about the code ! – a brand-new talk that’s aimed at 80% of developers. Short summary : “Most PHP developers focus on writing code. But creating Web applications is about much more than just wrting PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.”
  • PHP Tour in Lille, France on Nov 24-25, 2011 : Caching and Tuning fun for high scalability – the same talk as on T-Dose, in a condensed version

Working on…
In the next few weeks, expect a few new posts about :

  • A cool new IPv6 project we’ll launch soon
  • Some Zend Framework 2 news and stuff
  • More news on the Nginx module we’re building. At Zendcon, there were 3 large PHP hosters who were interested in testing the solution, so you can expect more posts on that.

Talks done and talks to come

I haven’t really been updating my blog lately because of time constraints. I do have a few interesting topics to write about, although some of those have already been converted to talks I want to give at conferences over the next few months (if I get accepted ofcourse).

About those talks : I gave a tutorial called ‘Caching and tuning fun for high scalability’ at phpBenelux in January. It was my first conference talk and I enjoyed it a lot.
So much in fact, that I submitted the same talk for Dyncon2011 in Stockholm in March, where I gave a slightly shorter, but probably much better talk (learned from some of the mistakes I made in the first talk). Slides of this talk can be found at Slideshare although waiting for the video recording might be better, since there’s a lot of stuff not being shown on the slides (such as the live benchmarks).
If you were there, feel free to rate my talk at Joind.in : phpBenelux or Dyncon.

Mid-June I gave a Zend Webinar titled ‘Creating fast, dynamic ACLs in Zend Framework’, where I discussed alternatives to Zend_Acl using reflection and caching. I was happy to see more than 80 people watching the live webinar and got lots of interesting questions. The video is available on the Zend Webinar site. Any feedback most welcome via SpeakerRate.
I promised to publish the code for the ACL implementation and that’s still on my todo list. I hope to be able to do this by the end of July (don’t want to make unrealistic promises…).

In the coming months, I’ll be giving the caching and tuning tutorial at FrOSCon (with a new bonus feature near the end… a first glimpse of a new feature for Nginx) near Bonn, Germany in August and at PHP Tour in Lille, France in November.

I’m not entirely sure if I’ll attend Zendcon 2011 yet. Although I promised Michelangelo Van Dam to help out with the Unconference last year, I had to cancel my trip due to my grandmother passing away on the morning of departure. Maybe this year I can actually keep that promise (if I can find the budget).

phpBenelux : conference done – slides up – webcast coming soon

phpBenelux 2011 was a huge success. After last year’s one-day conference the phpBenelux team decided to add a half day of conference and add a half day of tutorials as well. I wasn’t able to attend many of the talks, but heard a lot of good things about the talks, the food, the atmosphere, etc.

On Friday, I presented a tutorial called ‘Caching and Tuning fun for high scalability’ at the phpBenelux Conference. The slides are now available here (Slideshare). If you were at my talk, please rate it here (Joind.in). Since it was the first time I gave this talk, any feedback would be most welcome.

Sadly, because of issues with servers (2 disk failures and a burnt out CPU), I was unable to present the planned live benchmark, so I will do a webcast in March in which I will go through the step-by-step process of getting a site from having no performance and no scalability to the point where it can scale way beyond Slashdot-effect handling levels. That way, people who follow the webcast can see for themselves what effect each of the changes (adding the different kinds of caching, distributing the cache, adding Nginx, adding reverse proxies, tuning the DB, tuning the Webserver and ofcourse tuning the frontend) has on the performance and the scalability of the Website. It will definitely be an eye-opener for a lot of people !

For an exact date, check back here in Feburary or follow me on Twitter @wimgtr

Using PHPUnit to verify parameter types (revisited)

(This is an update on a blog post I wrote last year about parameter type checking)

PHP is dynamically typed

PHP is a dynamically typed language. What this means is that it allows you to do things like :

$a = 5;
$a = 'test';
$a = false;

The reason this works, is because PHP enforces type rules during execution, not at compile-time.

In many other languages this is impossible, since you need to define a type for the variable at compile-time. Languages such as Java, C, C++, C# and VB.Net are good examples of statically typed languages.

Problems with dynamic typing

Although dynamic typing is considered to be one of PHP’s strong suites, it does pose some problems. Let me illustrate with an example :

Suppose we have a piece of code that processes the amount of money each employee must be paid. Employees can file expense notes that are paid back in cash or when their monthly wages are paid. Our code will make the calculation for the pay check.

The data for our 4 employees is located in a CSV-file, made available from an external source :

employeeId, firstname, lastname, wage, expenses, processexpenses
1, Claire, Clarckson, 2000, 212, 0
2, Tom, Whitney, 1910, 111, 0
4, Jules, verne, 1932, 98, 1
5, Gregory, Jameson, 2131, 241, 0

If the last field is true, the expenses must be added to wage amount on the paycheck. So our code might look like this (don’t pay attention to code quality, it’s an example of ‘the average piece of code you will find’) :

class Wages
{
/**
* Process the wages
* @return boolean
*/
public function processWages()
{
$handle = fopen('some-file.csv', 'r');
while (($data = fgetcsv($handle, ',')) !== false) {
if (is_numeric($data[0])) {
$result = $this->processLine($data[2], $data[3], $data[4]);
$this->sendPaycheck($data[0], $result);
}
}
return true;
}

/**
* Calculate wages based on processExpenses parameter
*
* @param float $wage
* @param float $expenses
* @param boolean $processExpenses
* @return float
*/
private function processLine($wage, $expenses, $processExpenses)
{
if ($processExpenses) {
return $wage + $expenses;
} else {
return $wage;
}
}

/**
* Pay the employee
*
* @param int $id
* @param float $amount
*/
private function sendPaycheck($id, $amount)
{
echo 'Paycheck for id ' . $id . ' for the amount of : ' . $amount ."\n";
}
}

Everything works fine, until the external source decides (probably unknowingly) to modify the data format to :

employeeId, firstname, lastname, wage, expenses, processexpenses
1, Claire, Clarckson, 2000, 212, false
2, Tom, Whitney, 1910, 111, false
4, Jules, verne, 1932, 98, true
5, Gregory, Jameson, 2131, 241, false

When we run the code, everyone will be paid their expenses, even those that have ‘false’ in the last field. The reason ? The last field of each line might look like a boolean, but is in fact a string. The “false” is read as a string and is boolean true.

You might say that we didn’t follow best coding practices in our :

if ($processExpenses) {

which should have been

if ($processExpenses === true) {

but that would only have reversed the effect : nobody would have been paid.

Similar non-boolean situations cause the same problem. There’s a huge list of problems that might be caused by passing incorrect types to a function.

Granted, we should have put a type check in place, but as I said this was the average type of code you will find. And it’s exactly this type of code I wanted to use for this demo.

So what’s the solution ?

Since we don’t want to give up on our dynamic typing, we need a way to verify that parameters being passed to a function/method are of the type that we intend them to be. That way, anyone who wishes to use our function/method will be forced to pass the right parameter.

One solution would be to use type safe objects like the ones described by Sebastian Bergman (author of PHPUnit) in his Type-Safe Objects in PHP presentation. However, this is unusable for existing projects as it requires a massive rewrite. Furthermore, as Sebastian indicates, it poses a lot of new problems. And finally, it slows things down quite a bit, since it uses reflection to verify types during execution…

Another solution would be to have type hinting for all types, including scalar types, in PHP. Although proposed and agreed to by many, the current concensus (as of today at least) is to not include it PHP 5.4. It might end up in a branch for future use or might end up as a PHP extension down the line, but for now it seems to be off the table for PHP 5.4.

So should or shouldn’t we check the type of a parameter before using it ?

Another big dillema : should you check each parameter’s type in each single function at runtime using is_int, is_bool, etc. ? Some would say it’s the safest way and the only way to be absolutely sure.

I believe there’s a different and better approach : if you can integrate type checking in your unit testing and have a high code coverage percentage, there’s no need to explicitely check the type during runtime, except when handling external data.

So how do we make sure types are checked ?

What system is better suited for the job than the most popular testing PHP framework, PHPUnit ?

Since PHPUnit run can be repeated over and over again and introducing additional checks will not cause performance issues on the actual production environment, this is a good place to add these checks.

Upon execution of each PHPUnit Testcase, this patch will verify parameters for each of the called functions/methods. You can define the depth of calls using a PHPUnit command line parameter (the default is 2, which means functions called from the testcase itself and functions called from those functions).

How does the system know what types are expected if we don’t have type hints ?

The system presumes that if you’re using PHPUnit, you clearly know proper development methods. This also means you’ll be using docblocks to comment your functions.

So, since there are no type hints to rely on, it will instead rely on the types you specify in the docblock

It will analyze the docblock of each function/method and compare each parameter type with the expected parameter type. If it finds an inconsistency, it will produce a PHPUnit warning.

So does it support…

– Classes : yes

– Interfaces / Abstract classes / parent classes : yes, in fact if you specify an interface or abstract/parent class in the docblock and pass a class implementing/extending them, it will detect it as a valid type

– Multiple types definitions in the docblock : yes – separate them by a pipe (|)

– Return value types : yes – needs Xdebug patch, see below

Is it perfect ?

Nothing is… there’s a few problems at this point :

– If you want to analyze return values, you’ll need a patch for Xdebug I wrote last week. You can download that patch here : XDebug bug #416 patch

– It still needs a bit of tuning… it’s a work in progress !

The MySQL problem : something most people don’t know

Data from any external source might cause problems. MySQL is the best example : any data being returned from MySQL using the non-binary protocol is a string, even if the column is defined as int, decimal, bool (tinyint), …

MySQL’s protocol returns all data as a string and the PHP mysql and mysqli extensions don’t convert it into the expected datatype. The result is that any data from MySQL will be passed as a string, which can cause havoc when doing type checks. The only exception is when using mysqlnd and prepared statements (see the second example of Scalar type hints in PHP trunk).

There are 3 solutions to this problem :

  • Cast everything : not really fun, since you’ll need to change all your code. It might also be bad for performance, although it does set the types right ofcourse. Might be the best option for new code.
  • Use Propel or some other database layer, which does the casting for you… same performance problem ofcourse.
  • Wait until someone makes changes to the way MySQL and PHP communicate…

In the meantime, if you want to use the type checking, but you have some problems with MySQL, you can use a docblock tag to disable type checking for some functions : @phpunit-no-type-check

How to run it

After applying the patch to PHPUnit (and Xdebug if you want return type checking), run it like this :

php [path to phpunit.php] --check-param-types [TestCase.php|TestSuite.php]

Optional parameter :

–check-param-type-depth= sets the depth to which it needs to check parameter types. Your test is depth 0, any called function within your test is 1, etc. – default is 2 although 3 might be handy too

The output

This is the kind of output you can expect :

2) ATest::testMultiply

Invalid type calling A->multiply : parameter 2 ($factor2) should be of type int but got string(1) instead in C:\development\Test\ATest.php:42

Note that if you use the ‘–check-param-type-depth’ parameter and set it to a high number, you might see errors about libraries you use. Ofcourse, that might be the right moment to notify the library author (or contribute a fix yourself !)

Advantages

  • No need to use is_int, is_bool, etc. in a function that was type-checked
  • Consistent use of types
  • Developers will learn to focus not just on the content of a variable, but on the type as well. In time, it will become second nature to use the correct types from the start. Code hinting in most IDEs should in fact already help out with this, but now there’s a way to verify this too.
  • Verification of each function/method call, not just in terms of functionality (PHPUnit’s job), but also in terms of data types
  • Forces developers to keep the docblock up-to-date (!)

Using type checking basically brings the best of the dynamically and statically typed worlds together : you still have the flexibility of dynamic typing, but assurance that functions are called with the parameter types they were designed to be called with (as well as return the correct types). It’s the perfect middle-of-the-road approach for teams with a mix of ‘strict’ and ‘not-so-strict’ developers.

Where to get it

The PHPUnit modification can be downloaded through a Github-fork : http://github.com/wimg/phpunit

Possible extension

There’s plenty of things that could be added.

One of them is “non-strict” option, which ignores type conversion between types as listed on http://wiki.php.net/rfc/typecheckingstrictandweak (option 2 section)

Feedback

As always, feedback is much appreciated, as a comment in this blog or via e-mail.