Archive for June, 2009

June 3rd 2009

SPL: a hidden gem

By a show of hands, how many people here ever heard of SPL? How many already used it? Chances are most of you didn’t raise your hands, and some might even have a confused look on their faces. Indeed that is the sad reality when it comes to SPL, but What is SPL?

SPL, or Standard PHP Library, is a set of classes and interfaces built in to PHP since version 5.0, and as of PHP 5.3 it cannot even be disabled, so its here and for good. Its actually hard to disable it when compiling, so 9.9 out of 10 changes that you have it. But why have you not used it? The answer begins at “poor documentation” and ends in “didn’t even know it existed”, SPL has not had the “bling” about that it deserves, but this is where this article comes in, time to turn this around. So what is in SPL?

SPL makes available a few hooks for overloading the PHP Engine, such as ArrayAccess, Countable and SeekableIterator interfaces, to make your objects work like arrays. You can also manipulate other stuuf using RecursiveIterator, ArrayObejcts and various other iterators. It even has classes for specific points such as Exceptions, SplObserver, Spltorage and helper functions to overload other aspects, like spl_autoload_register, spl_classes and iterator_apply. Overall its a swiss army knife of code that can be implemented in PHP but that because of its hooks will probably perform much faster in SPL. So, what can i actually do with it then?

Overloading autoloader

You are a by the book programmer, and after __autoload came around you rewrote all your sites and remove the endless stream os includes and requires in your code to make way for lazy loading, right? So once in a while you found yourself in a jam, you product’s classes use a specific naming/directory structure and the Zend Framework classes you use have a “_” to path approach, how do you solve this? Giant __autoload that includes all logic, trial and error style? Alter you directory structure to Zend’s? No! Overload it!

The process is simple, just create your own autoload function and overload it, that way the autoload procedure will run the class through Zend’s loader, if it does not find a class, it will then run yours, and keep on going down the line until one of them finds it.

    1 <?php
    2
    3 class MyLoader{
    4     public static function doAutoload($class){
    5         //autoload process
    6         //use file_exists please
    7     }
    8 }
    9
   10 spl_autoload_register( array('MyLoader', 'doAutoload') );
   11
   12 ?>

Iterators

Iterator is a design pattern, a generic solution to iterate over data in a consistent manner, a way to access elements of an object in a sequential way without exposing underlying representations. SPL has all the Iterators you ever need, and i’m not exagerating at all. This also includes iteratorfilters and so many other. You can use this for example in you database results, making the DbResult object implement the Iterator interface, thus making functions such as next(), prev() and other available so you can iterate results in a foreach. Another good example for Iterators is transversing a directory. In the usual manner you can iterate over scandir, the use if and elses to skip over “.”, “..” and any other files, say for example you want just the pictures from a directory. You can do all this using iterators and iterator filters, like in this example:

    1 <?php
    2
    3 class RecursiveFileFilterIterator extends FilterIterator
    4 {
    5     protected $ext = array('jpg','gif');
    6
    7     /**
    8     * Takes $path and creates a recursive iterator with a directory iterator
    9     * @param $path diretory to iterate
   10     */
   11     public function __construct($path)
   12     {
   13         parent::__construct(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
   14     }
   15
   16     /**
   17      * Checks extension names for files only.
   18      */
   19     public function accept()
   20     {
   21         $item = $this->getInnerIterator();
   22         if ($item->isFile() && in_array(pathinfo($item->getFilename(), PATHINFO_EXTENSION), $this->ext)) {
   23             return TRUE;
   24         }
   25     }
   26 }
   27
   28 // Using it
   29 foreach (new RecursiveFileFilterIterator('/path/to/something') as $item) {
   30     echo $item . PHP_EOL;
   31 }
   32
   33 ?>

You may argue that now you have much more code, I’ll reply: yes, but you have reusable and testable code!

Here are some more iterators:

  • RecursiveIterator
  • RecursiveIteratorIterator
  • OuterIterator
  • IteratorIterator
  • FilterIterator
  • RecursiveFilterIterator
  • ParentIterator
  • SeekableIterator
  • LimitIterator
  • GlobIterator
  • CachingIterator
  • RecursiveCachingIterator
  • NoRewindIterator
  • AppendIterator
  • RecursiveIteratorIterator
  • InfiniteIterator
  • RegexIterator
  • RecursiveRegexIterator
  • EmptyIterator
  • RecursiveTreeIterator
  • ArrayIterator

As of PHP 5.3 we have some other interesting tools, like SPLInt and other types you can use for type-casting (in PECL still). One class worth mencioning however is:

SplFixedArray

Why? Its faster! Why? aha! that’s the million dollar question. See to understand that we must dwell into the PHP internals for a regular array. In a regular array you can use diferent types of keys, i.e. numeric, strings and so forth. What PHP does is that it does not use that value as a key in the underlying C array, rather it hashes whatever it gets and uses that as a key, so hashing has a performance cost. SplFixedArray only accepts numeric keys, so no hashing happens! For those of you that cought up, yes, its a C array! So that explains why this is faster than regular arrays. (only php5.3!!)

This are just some examples of what you can do with SPL, unfortunatelly there is no “one place” to go and get a complete view of SPL, tou can hit the regular manual, but you should always trust in this documentation, done by the creators themselves, or you can hit Elizabeth’s Blog, most examples on this article belong to her.

Invitation

But there is no better way to get better at SPL than contributing to it! We need documentators! So if you want to be part of PHP and help out, check out the php.doc mailing list, or IRC your way to EFNet and join #php.doc and say “I want to help”, you will be given a task very fast!

1 Star2 Stars3 Stars4 Stars5 Stars (Sem votos registrados)
Loading ... Loading ...

11 Comments »

June 1st 2009

php|tek 2009: The community in action

This year I was abel to attended the 2009 php|tek conference in Chicago. This conference is hosted by MTACon, the company behind php|architect magazine, one of the most influent PHP publications in the world. php|tek is a unique event in its overall “feel” and purpose – for those that read my post on ZendCon’08 you may be able to pickup this difference yourselves. Tek is a community oriented event, as opposed to ZendCon which is much more aimed at companies. Is this good you ask? Yes, its perfect, it in no way falls short of the content in ZendCon, but on the plus side it gives one many more opportunities to mingle and meet the central PHP Core Developer Team, and most importantly, it inspires attendees to work with and give back to PHP.

Same as last year, the conference was held in Chicago, IL in the Unites States at the Sheraton Hotel, a wonderful venue that helps keep everyone close by during the conference and during “off-time”. The conference ran for three days plus a tutorial day – from May 19th to May 22nd. The day before the start one could already see many of the most well known PHP developers arriving – it appeared that the Core team was arriving early to host a PHP Dev meeting held at Microsoft. And the topic of the conference .. ? PHP 5.3.

The sessions were great, and tutorials day featured particularly interesting sessions, of which I attended a security talk to complement my PHP Security skills,as well as a Code Review Session. This session, held by Sebastian Bergamann, Stefan Priebsch and Arne Blankerts was extremely interesting, we dove deep into the code of some major frameworks and apps, like Magento, Wordpress, Habari and found some incredible (not in a good sense) pieces of code. This talk showed me a different side of things especially for certain areas of coding where I can certainly do better. It also gave me a new perspective on code reviews, which have today a much bigger importance then before.

The rest of the sessions during the event were really good, some were inspiring (Security Centered Design), some made you wish PHP 5.3 was out (PHP 5.3 – Hot or not?), some made incredible associations to drive home the importance of a good development environment (The Knight Rider Methodology to Software Development), some showcased the more obscure but very useful parts of PHP (SPL to the Rescue), some even tried to point you in a good direction (Untestable Code). There really were sessions for every kind of developer, from the “regular joe” to the php expert – at times I wished I had the method __clone implemented on myself, so I could get to all sessions. Also, alongside the event we had great UnCon Sessions and an Hackathon organized and led on by the community, with some simple but great sessions.

This leads me to the biggest feature of php|tek, and one most commonly overlooked by developers and managers alike, namely the community. This was by far the biggest difference from ZendCon, a total focus on the community and hence, a focus on geting everyone active. The PHP comunity has been in focus during the last few months. Since the news of PHP 5.3 was released we have seen an increase in activity inside the PHP community: BugHuntDays, TestFest09, documentation, patches, you name it the community has done it this year. User Groups keep growing and popping up everywhere. Just in Brazil we have had at least 5 groups started since last year. The conference fosters the

The recipe for success in this sense is not clear, was it the community oriented sessions (A guide to using and understanding the community, User Group Meetup)? The after-hour programming (PechaKucha night, Retro Gaming Night, Hackathon)? Maybe it was the breakfasts and lunches where you shared tables with all the active members of the community? The discussions around a cup of wine? I’m guessing it was a combination of all this, the sheer exposion to all this is enough to get you into the “giving back” mood. The ingredients are pretty simple, knowing where you can help, who to ask, where to read about it and a touch of “karma”. Many moments at tek were based on this, the interaction with great names of the community and a clear picture of what PHP needs. The whole experience shows you clearly that not Zend, ibuildings, IBM or Microsoft are in the control of PHP, we are, the community has grown.

PHPdeveloper.org has talked about this and I can see it myself, PHP has matured, coming out of its teenage years of rebelty and strange changes, and moving now to its mature Adult years. But not only the language, the whole of the PHP Community has tagged along, the core developers show more leadership, the community no longer takes a step back, it now steps forward, opinating, working, committing, participating.. no longer a bystander. During the closing notes the crowd was asked to stand up, not all at once, but in an order of “community activity”, it was amazing to see how many people were standing up in the end, from Core developers, extension developers, translators, documentators, testers, UG leaders to the PHP teacher at his company’s office we had almost a full room standing, leaving maybe 10~15% of people that are not active present in the event.

This is the message that Tek brings with it, the maturity of a language we know for so long, which fits right into ZendCon’s message from last year, “Why not PHP?”. Another indication that community was in focus was that some session focused on making the developers life easier, with frameworks, version control techniques and so many orders. Different from other times, sessions did note revolve around asking if a framework is enterprise-ready, they revolved around comparing various frameworks, deemed enterprise-ready, and how you should choose your framework. One of the features displayed for each framework was the community behind it, showing us once more that the community does make a difference and not only for PHP but for all the pieces we use on a daily basis.

If tek leaves me with a message I can take back to fellow developers and UG members it is: “Step up, contribute to PHP, help out with what you can, any little thing you do will come back around to you, writing tests will make for a better 5.3 release, and that will surely make life easier for you, it does not take too much, even small things like writing documentation, just get active, wear you PHP shirt and go for it.”

As for the managers, deccision makers and leaders, i leave you with this message: “Believe in PHP, invest in the community and in your employees, growing the language will grow your business, giving back to PHP will eventually give back to you. Promote that message in your office, employees who invest in PHP gain more knowledge about it, giving your solution more quality.”

(most of the talks mentioned here and most of the ones presented at php|tek09, can be found on slideshare)

First published at: http://www.mihswat.com/2009/05/31/phptek-2009/

1 Star2 Stars3 Stars4 Stars5 Stars (Sem votos registrados)
Loading ... Loading ...

1 Comment »