SPL: a hidden gem

  • PHP
  • June 3, 2009

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.

111123456789012<c}s??lp>palhs_psp}auuMbtyloLiloc/oaauadsusdette_raor{tlfeioigcalidesf_tupeenrxrcoi(tcsietaossrnsrpadlyoe(Aa'usMteyoLlooaadde(r$'c,la'sdso)A{utoload'));

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:

111111111122222222223333123456789012345678901234567890123<c{}f}??lo>parhsUepspp{}p{}saeruuiccRoT@bbnhhetaplClgocekaiphi$i}(ucercaecifin$rtsarctteisemfekfe(wtid$unsum$revp$ntnieRme$apc:ec=tteFetat:xteuc.ixhti_ti$mrultho_eot-nrPeancnnh>sHF=ndosiiTiPidiniassRv_lar_soc-FUeEtrcectnc>iEFOerrtoregl;iLraeonunpeel;Iyarscatt(et(tyttm(I)Fe'er(e)nirjstunsn&lapocee&ttgatwfreo'i(oIirr,rt$RrtnI'eepee_tegcracfraexiuatuiarrtfrthrltrae'se)seoatn)iisryod;vv((rseeo)p(In;a'Fitlt/iteyhpler.iatranteatfhrtoo/Ior(ttrI$oeti/rwetsaireottammoht-ero>targh(eidntnieFgrwi'el)cRetenaocasrumyre$s(iii)ttv,eeemrDP)aiAtrT{oeHrcItNoFrOy_IEtXeTrEaNtSoIrO(N$)p,at$ht)h)i)s;->ext)){

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!

comments powered by Disqus

Related Posts

Screencast: Utilizando o dmsAutocomplete com banco de dados

Screencast: Utilizando o dmsAutocomplete com banco de dados

  • January 10, 2008

Uma das perguntas que mais respondo pelo blog é “Como faço para utilizar o dmsAutocomplete com registros da base de dados?”. Além disso, a muito tempo procuro uma “desculpa” para fazer um screencast. Decidi então juntar estas duas situações e fazer o primeiro screencast da DMS Systems.

No video apresentado neste post vou demonstrar como fazer uma simples adaptação ao script PHP que vem incluído no dmsAutocomplete para que o mesmo busque dentro de uma base de dados e não mais dentro do texto como o exemplo demonstra. Usarei uma base de dados mysql simples e farei as conexões e busca de resultados utilizando as funções básicas do PDO, portanto se não conhecem esta nova camada OO de abstração de conexão com a base de dados, sugiro que procurem sobre, pois ela facilita e organiza bastante o trabalho com base de dados no PHP.

UPDATE: No momento o serviço que hospeda o screencast esta offline, o screencast deve voltar na quinta ou sexta

UPDATE: Screencast no ar novamente

Read More
Desinformação na mídia: PHP rotulado como vírus

Desinformação na mídia: PHP rotulado como vírus

  • July 29, 2011

Recebi hoje pelo twitter (do colega @leoviena) um link para uma matéria da do Jornal Hoje na Rede Globo, ao assitir a matéria fiquei abismado com as informações dadas na matéria. (UPDATE: matéria em texto)

Read More
AJAX e PHP: Aprendendo a base [Parte 1]

AJAX e PHP: Aprendendo a base [Parte 1]

  • August 19, 2008

nota: Este artigo foi publicado pela primeira vez na Quarta Edição da Revista PHP Magazine em março de 2008. Estou agora re-publicando ele aqui em duas partes, 1 e 2, para melhor visualização

Neste artigo, pretendo apresentar ao Leitor a tecnologia AJAX, resolvendo algumas confusões sobre o que realmente é, e como e onde deve ser usada. Este artigo apresenta um exemplo de como implementar uma solução AJAX sem auxílio de Frameworks. Após palestrar sobre o assunto no 1º PHPDF RoadShow (E no PHP Conference 2007 em São Paulo) decidi por todo material das palestras em um artigo, que foi publicado pela primeira vez na PHP Magazine, e que agora re-publico aqui em meu Blog. Esta primeira parte esta dividida em duas pois descobri que meu WordPress fica louco com artigos grandes. E e breve este artigo terá uma sequencia que entrará no uso de FrameWorks.

Desde que comecei a pesquisar sobre AJAX devo admitir que me apaixonei pela forma que ele permite executar tarefas simples e avançadas de forma amigável, simples e ágil. Desde então, tenho procurado repassar este conteúdo, contribuindo brevemente com o site AJAX Online (www.ajaxonline.com.br) e publicando diversos artigos em meu blog pessoal.

Read More