Latest News
PHP 5.3.3 Namespaces
Purpose of the entry
With PHP5.3.3 recently released I really feel it is time that php developers are taking namespaces seriously. If you don’t I guarantee you will be out of a job within five years. Namespaces are a fundamental part of the future of PHP.
The big frameworks like Symfony and Zend Framework have understood this and build their latest versions (2.0) with namespace support.
You all have namespaced before using the filesystem and long class names. This is still a valid way to go, but as time evolves you will see this less and less. Probably the filesystem structure will remain but not the long tedious names. We will start to use aliasing or namespace scopes for that.
Overview
- Getting started with namespaces
- resources
Getting started with namespaces
So how does one begin with namespaces? Well simply by doing it. And what better way do to it than by example.
In this blog post I will explain how to use namespaces in a project and how to import two external libraries into it.
One your own and the other a real third party.
It is a small project and solely for demonstration purposes, kept intentionally very small but explanatory by nature.
So do not heckle me for design decisions and such, those would only cloud the goal of this small presentation.
You can download a working copy of the project so you can play with it and experience namespaces first hand.
namespaces.zip
I will wait a minute or so.
Done and loaded in the browser? Great, let’s get on with it.
As you see I first put all code outside of my public folder (httpdocs). I have put everything regarding setting include_paths
and constants in Application.php.
// Application.php
<?php
namespace {
error_reporting(E_ALL);
ini_set('display_errors', true);
function __autoload($class) {
$class = str_replace('\\', '/', $class);
$class = preg_replace('/^Application/', 'application', $class);
require_once $class.'.php';
}
set_include_path(
realpath(dirname(__FILE__).'/../').PATH_SEPARATOR.
realpath(dirname(__FILE__).'/../library')
);
}
namespace Application {
const PROJECT_PATH = '../';
$bootstrap = new Bootstrap(new \Nick\PlayBowl());
$bootstrap->run();
}
The file itself contains procedural code with two namespaces. You can attach as many namespaces as you want inside a file by encapsulating them between brackets. The namespace operator must be the first thing defined in a file.
In Application.php we have a global namespace in which we will register the autoload and setup the include_path. Autoloading namespaces
has to be done in the global scope. It also makes sense to set the include path in the global scope. Everything related to our application
itself goes into the Application namespace.
We will load the Bootstrap class from the namespace Application. Class names that do not contain a backslash like Bootstrap can be resolved in 2 different ways. If there is an import statement that aliases another Bootstrap to Bootsrap, then the import alias is applied.
Otherwise, the current namespace name is prepended to Bootsrap. Because we did not use the use operator no aliasing or importing is done, and Bootstrap will resolve to Application\Bootstrap().
Because no leading backslash is used when we defined the “namespace Application” we have specified an unqualified name. PHP will resolve this by adding the namespace to the current used namespace. In this case it is the \ (global) namespace.
// Bootstrap.php
<?php
namespace Application;
class Bootstrap
{
protected $_game;
public function __construct(\Nick\PlayBowl $game)
{
$this->_game = $game;
$this->_setupSomeUglyNamedNameSpace();
}
public function _setupSomeUglyNamedNameSpace()
{
\SomeUglyNamedNameSpace\Exception::setLogFile(namespace\PROJECT_PATH.'/logs/application.log');
}
public function run()
{
$this->_game->aim();
$this->_game->roll();
$this->_game->getHits();
}
}
Inside the Bootstrap.php file we have used the namespace operator to register the class Bootstrap under the Application namespace. We
did this by opening Application as the current namespace and then adding constants, functions and or classes to it. In our example the class Bootstrap.
Making it available by calling it from outside the current namespace using \Application\Bootstrap(); Just as we did with \Nick\PlayBowl in Application.php. As you can see we can also force the type in the constructor using namespaces just as we did with long class names.
In \Application\Bootstrap we use already 3 namespaces: Application, Nick and SomeUglyNamedNameSpace to target specific functions, constants and classes.
we have two different use cases for the namespace operator. Outside a namespace we switch the scope to a new namespace using namespace nameOfScope and inside a namespaced scope we can use the operator to target the current scope. This making the namespace operator the equivalent of the class self:: operator.
We have registered an instance of \Nick\Playbowl to $this->_game and we call its methods in the run() method. Let us take a look at that.
Because here you will see aliasing.
//PlayBowl.php
<?php
namespace Nick;
use \SomeUglyNamedNameSpace as Lib;
class PlayBowl
{
public function aim()
{
echo 'you are aiming at the pins<br />';
}
public function roll()
{
echo 'you release the ball and wait in anticipation<br />';
}
public function getHits()
{
$this->_hit();
$this->_hit2();
$this->_getPinsHit();
$this->_getPinsHit2();
$this->_getPinsHit3();
$this->_getPinsUnexisting();
}
protected function _hit()
{
$calculator = new Calculator();
if ($calculator->isGood()) {
echo 'you hit all pins<br />';
}
}
protected function _hit2()
{
$calculator = new namespace\Calculator();
if ($calculator->isGood()) {
echo 'you hit all pins<br />';
}
}
protected function _getPinsHit()
{
$someCalculator = \SomeUglyNamedNameSpace\Calculator::factory(\SomeUglyNamedNameSpace\Calculator::SCIENTIFIC);
$num = $someCalculator->add(2, rand(2,4));
echo sprintf('%d pins hit', $num),'<br />';
}
protected function _getPinsHit2()
{
$someCalculator = Lib\Calculator::factory(Lib\Calculator::SCIENTIFIC);
$num = $someCalculator->add(2, rand(2,4));
echo sprintf('%d pins hit', $num),'<br />';
}
protected function _getPinsHit3()
{
$someCalculator = new Lib\Math\Addition\Scientific();
$num = $someCalculator->add(2, rand(2,4));
echo sprintf('%d pins hit', $num), '<br />';
}
protected function _getPinsUnexisting()
{
try {
$someCalculator = Lib\Calculator::factory('science');
} catch (Lib\Exception $e) {
$e->log();
}
}
}
Ok a lot is going on in here. Or so it seems… What I actually have done is included a lot of duplicate code for your pleasure.
let us first take a look at hit() and hit2(). Those two are identical. My preference is the hit() method. I will explain.
This method is identical to hit2, but this function doesn’t use the namespace operator, because by default PHP will prepend it with the current namespace. In hit two we explicitely use the namespace operator and so we manually prepend the current namespace to the classname. In hit2 the namespace operator is the namespace equivalent of the self operator for classes.
Time to take a look at the _getPinsHit methods. Again these are example methods. Were in _getPinsHit we use the third party library SomeUglyNamedNameSpace and use the fully qualified namespace (leading backslash in the namespace).
_getPinsHit2() does exactly the same thing but here we use the namespace aliasing functionality. We have at the top of the file defined the
namespace alias with the use of the use operator. use \SomeUglyNamedNameSpace as Lib; Thereby effectively shortening that uglynamespace or preventing namespace clashes.
_getPinsHit3() goes further into that example by showing that you can easily use that aliased name as the base for nested namespaces.
Note that you can not have real nested namespaces like you can have nested ifs. You can only have nested namespaces like you can have nested classnames. Thus by appending the namespace names, extending the scope. Like in this example. The class Scientific is a part of the namespace Lib\Math\Addition\ which in his turn is a part of \Lib\Math\ and so on…
_getPinsUnexisting Doesn’t really demonstrate something in this class but I needed to show you the difference between global namespace functions and other namespaced functions.
But first let us take a look at the other usage of the use operator. The import usage. This will be used a lot to shorten names.
//Calculator.php
<?php
namespace SomeUglyNamedNameSpace;
use SomeUglyNamedNameSpace\Math\Addition;
class Calculator
{
const SCIENTIFIC = 'scientific';
static public function factory($type = 'scientific')
{
if (self::SCIENTIFIC === $type) {
return new Addition\Scientific();
}
throw new Exception('you must specify a valid Calculator type');
}
}
We used to do “return new SomeUglyNamedNameSpace_Math_Addition_Scientific();” , now with namespaces we can finally shorten it with:
use SomeUglyNamedNameSpace\Math\Addition; and from then of on you can call in the current scope simply “return new Addition\Scientific();” Which makes your code much easier to read.
Ok of to our final piece of example code:
//Exception.php
<?php
namespace SomeUglyNamedNameSpace;
class Exception extends \Exception
{
static protected $_logFile;
public function log()
{
file_put_contents(self::$_logFile, 'this will call the namespaced function');
\file_put_contents(self::$_logFile, date('H:i:s')."\t".'this will call the global function, which we all know');
}
static public function setLogFile($path)
{
self::$_logFile = $path;
}
}
function file_put_contents($filename, $string) {
echo 'this is '.__NAMESPACE__.' function';
}
I know in good design the last function should not have been in that same file, but this example if for the understanding of namespaces and nothing else. It isn’t a real Bowling game either
Ok what is going on?
We first Extend the global Exception class which we all use everyday and implemented a log() method.
This log method does two things. It first calls the file_put_contents as an unqualified namespace (no backslash operator in the name found).
As before this will have the effect that it will first try to prepend the current namespace to the function and thus will find the function at the bottom of the file. And secondly we call explicitily the good file_put_contents, the global scope version! Which will nicely log the error message to the log file setted in our Bootstrap.php
I hope this small presentation on namespaces made a lot of things clear.
resources
- php.net manual on namespaces
- Zend Framework 2.0 roadmap
- Symfony and PHP5.3
- The sample project for download and playing
See you soon,
Nick Belhomme
Dutch PHP Conference 2010 (#dpc10)
Purpose of the entry
For those who don’t know me, I always do a small write-up on each conference I attend (it is to persuade all you non-attendees to be there next year and maybe say hello).
This write-up will be on an incredible event packed with lots of interesting topics, relaxing atmosphere, interesting people to meet AND goodies to win. In short the Dutch PHP Conference. And this year it got even better.
Overview
- What is #dpc10?
- Yes! I spoke at the Dutch PHP Conference
- Who was attending?
- Pros and Cons of this year
- Conclusion
What is #dpc10?
The Dutch PHP Conference is an event organized by ibuildings and spans 3 full days.
One tutorial day and 2 conference days. Generally the talks cover the more advanced PHP related topics. This year was the fourth installment of many more to come and was hosted by Lorna Jane Mitchell.
Compared to the previous years there was a new feature: the Uncon organized by PHPBenelux. The uncon is a less formal main stage at the conference where beginning and experienced speakers can bring their topics under public attention. You get requested the same day to speak in a certain time slot or you can volunteer to talk. If accepted your name will be listed next to the main speakers topics.
Yes! I spoke at the Dutch PHP Conference
I spoke about the good practice on separating different responsibilities of your application. It focused on
- a model is NOT your database
- how models retrieve results in the form of collections and entities from your Data Access Object (Dao, this might be
the database logic or a web service). - Why it is a good idea to implement using a factory (or even dependency injection) and not hardcode your dao inside each model.
- Creating a dao interface (contract based design) so that when you want to switch to another implementation, the model requires no change.
- that with this system (what OOP is all about) you create clear separation and unit testing is made very easy.
- you promote loose coupling
- Easy creation of extra layers by the use of decorators
It was a completely unprepared lecture, because it was a “Hi Nick fancy to speak” kind-of-a-thingy. I am glad I accepted because I received very positive feedback and generally people wanted more. You can see the comments on my talk on joind.in
Who was attending?
Approximately 400 attendees with the “open source state of mind” at heart joined the conference. People who love to learn or lecture
on everything programming related. It is about so much more than PHP. I urge you to join even if you are programming into a different language like .net or java. There is a wealth on information at this event and you feel the positive vibe of each and every attendee.
The sponsors gave away some cool gifts too, with Microsoft taking the lead. The raffle included a full week to Las Vegas, an XBox360, programs and much more. Microsoft is really starting to embrace the PHP Community by sponsoring almost each PHP Conference, for which the community is very grateful.
Pros and cons this year
Pro:
- better stage venue
- lots to learn at great lectures
- lots of awesome people who are happy to meet you
- an awesome feature called uncon sessions which is already fully adopted at United State conferences
- conference social drink at a local pub sponsored by GitHub => Free drinks for everyone
Con:
- like every year, the food is a bit disappointing. Prepare yourself to eat very basic sandwiches for 3 days. (The organizers could learn something from PHPUK, they serve awesome food, see my previous post)
Closing notes
Great value for money and in general a conference you should attend, no excuses.
See you next year at The Dutch PHP Conference 2011 (9-11 June 2011).
Thx for reading and feel free to comment,
Nick Belhomme
#PHPUK2010 aka PHP Uk Conference 2010
Purpose of the entry
Like every year I love to attend this awesome conference. It sets itself apart in luxury, detail and talks. This year it was held in the Business Design Centre London. And what a cool venue this is. It is big, very modern and in the heart of London, just near St. Pancras. Which makes it very easy to reach. The reason why I am writing this review is I owe it to myself. You just have to brag about the fact that you attended this congress. And what better way to do it than to let the world read it. In the mean time giving the world a small glimpse on what it means if you attend this conference. By writing this post I hope I will convince people to attend the phpuk2011 which will be held on 25th Feb 2011 (yes they have already set a date, same as the one for 2010, I spot a pattern here…). And you can bet I will be attending then again.
Overview
- What is phpuk2010?
- Who was attending?
- My 50 cents
- Pros and Cons of this year
- Closing notes
What is phpuk2010
It is an annual PHP conference, powered by PHP London, this year being the fifth. Typically it is a one day conference which attracted this year approximate 450 attendees and an excellent line-up of speakers (of which I will review their talks later on my blog). It is so much more than just presentations on the latest and hottest topics around PHP. It is a event that invites, because of its relaxing nature and well designed schedule, for excellent networking possibilities. Some congresses tend to hurry the attendees from talk to talk without any breaks. PHP London organizes this conference a little bit different. They ensure that between each talk there is at least a 5 minute break. This gives you that time to network and let your brain rest for five. Which is necessary if you do not want to have a brain meltdown and looze focus during the talks. The organizers Scott, Matt, Jo, Dave and Franck know how important this is and do not loose track of this feature. Because the talks are very impressive. Take a look at the following schedule.
Who is attending this conference
Developers, managers, stake holders / investors, speakers, sponsors and much more. Enough interesting people to network. This year you had a pick of 450 people to talk to. Learn what drives other developers, learn new stuff from the speakers, do informal job interviews with managers, sell your project to investors, learn new technologies or opportunities at sponsor boots, maybe even win some prizes. To be short: an interesting bunch of people all waiting to talk to you and learn a little bit of what occupies your world. Maybe both worlds can align now or in the future. That is what networking is about. I generally have at least 15 extra people follow me on Twitter after or during a conference. Yes even during, because let us not forget we are talking PHP, most of the attendees are connected to the Net and are so hooked on it that they will even bring their laptops to be connected to each other during talks. You can see them comment on twitter, put pictures online on flickr or rate the talks on Joind.in and all this while the conference is in progress. The community is a busy crowd, it is alive and vibrating. And this community is non stop growing and attending the conferences world wide. PHPUk being one of the best. I also like very much the DPC (Dutch PHP Conference), typically a 3 day event organized by Ibuildings. See my review for the 2010 edition.
My 50 cents
PHP UK conference is an excellent conference with a great selection of speakers, excellent venue (this year being better than previous year) , outstanding service (first class warm dinner and all day round drinks a volontee), and a social event you cannot afford to miss.
Pros and cons this year
Pro:
- great venue : Business Design Centre London
- excellent speakers line up
- great sponsors with lots of prizes to win
- first class food and drinks
- happy atmosphere
Neg:
- If you attend a lot of conferences you will see a lot of the same speakers with the same topics returning
- Some rooms had a very annoying air conditioning, making it unbearable to sit at some spots, because of the cold air current.
- Some important mailing info could be a little bit more up front and not the day before.
Closing notes
great value for money and a special thanks to the organizers for making this a perfect day. Mentally I already booked to attend the next edition.
Sunny greetings from Belgium
Nick Belhomme
ps. The next blog posts reviews on the talks.
Zend Framework Form : Mastering Decorators
Hi dear reader,
today I am presenting you a workshop on how to master the Zend Framework form decorators.
I hope after taking a look at the code examples and explanations it all comes together and you will have a good understanding on how to use them.
Once you understand them you will start to love them, as it is a very easy way to write forms this way.
Sunny greetings and above all enjoy,
Nick Belhomme















I hope you have fun reading up on my latest adventures and discoveries. If you have any questions or suggestions feel free to email me at “contact AT nickbelhomme.com”