<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>MIH SWAT &#187; php</title>
	<atom:link href="http://www.mihswat.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mihswat.com</link>
	<description>Headquarters of the Strategic Worldwide Applications and Technologies Team</description>
	<lastBuildDate>Tue, 31 Jan 2012 09:59:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>php&#124;tek 2011 and what&#8217;s trending</title>
		<link>http://www.mihswat.com/2011/06/02/phptek-2011-and-whats-trending/</link>
		<comments>http://www.mihswat.com/2011/06/02/phptek-2011-and-whats-trending/#comments</comments>
		<pubDate>Thu, 02 Jun 2011 13:11:54 +0000</pubDate>
		<dc:creator>Rafael Dohms</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tek11]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=2820</guid>
		<description><![CDATA[Another edition of php&#124;tek has come and gone and this year some very amazing topics came into view. The conference itself was once again a great experience, great people, incredible speakers, lots of activities and incredible hack-a-thons and unconference sessions. &#8230; <a href="http://www.mihswat.com/2011/06/02/phptek-2011-and-whats-trending/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Another edition of php|tek has come and gone and this year some very amazing topics came into view. The conference itself was once again a great experience, great people, incredible speakers, lots of activities and incredible hack-a-thons and unconference sessions.<span id="more-2820"></span></p>
<p>Cloud computing is reaching a level of maturity in the technology market as a whole, finally finding its place and purpose and dropping the “silver bullet” tag. This seems to reflect on the language as well and many sessions revolved around using the cloud to complement projects and on how to take advantage of cloud aspects in a PHP architecture, as well as the many cloud offerings available.</p>
<p>Another topic that kept us all busy was Mobile development, which following the incredible rise of the smartphones and the various systems like iOS, Android and WP7 was also present in multiple tags teaching how to architect your app and create solutions that would work for all smartphone users out there.</p>
<p>I was very surprised this year to see a the clear presence of Applications in the event. WordPress, Drupal and sites like joind.in made their presence in various aspects, ranging from talks, to coding sessions and especially to representatives who took their time to talk to the speakers and attendees.</p>
<p>APIs and integration with external tools was also a hot topic. Many sessions described the many tools that can be used to improve your application, like queues, protocols, services and so many more, also how to develop api into your code so that your application can also be used as an external tool in another project.</p>
<p>One topic that i would love to see more and more was also present: Soft skills. This is a very important area to be explored by the community in general, some conferences like <a href="http://daycamp4developers.com/">DayCamp 4 Developers</a> already do a great job of covering them but they also grow in various others. These skills or just plain recommendations are fundamental to new and old developers so they can find new paths and grow in their own careers as they do it.</p>
<p>I must also reserve space for the Hack-a-thon which was a complete surprise and success this year, seeing somewhere around 90 developers hacking into the night or just plain learning from each other was quite a pleasing experience. I myself had a great time explaining the importance and the first steps needed to develop PHPT tests to cover PHP’s source code, its not about how much work is done in these events, but its about planting that very important seed that will keep growing after the event, and I was very glad to see so many reach that stage during the event.</p>
<p>Congratulations to the organizers and to all the speakers for delivering incredible content and for taking all developers under their wing to teach and interact. I had a great time also speaking to everyone about Windows Azure and architecting for the cloud, and I hope everyone at the session had a great time learning, even tough my voice decided to play a hoax on me and make me sound like a game of “fill in the blanks”. If you were at the session I would love to hear your feedback, please do it over at <a href="http://joind.in/talk/view/3417">joind.in</a>, also you may want to see the slides, so please go ahead and see them <a href="http://www.slideshare.net/rdohms/open-a-window-see-the-clouds">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2011/06/02/phptek-2011-and-whats-trending/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Smarty Trap</title>
		<link>http://www.mihswat.com/2010/08/02/the-smarty-trap/</link>
		<comments>http://www.mihswat.com/2010/08/02/the-smarty-trap/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 07:47:01 +0000</pubDate>
		<dc:creator>Neil Broers</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[smarty]]></category>
		<category><![CDATA[template engine]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=1534</guid>
		<description><![CDATA[Recently I went to Luke Welling's presentation entitled "PHP in the 21½th Century" at OSCON. He mentioned something interesting that got me thinking, something he calls "The Smarty Trap". <a href="http://www.mihswat.com/2010/08/02/the-smarty-trap/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Recently I went to Luke Welling&#8217;s presentation entitled &#8220;PHP in the 21½th Century&#8221; at OSCON. He mentioned something interesting that got me thinking, something he calls &#8220;The Smarty Trap&#8221;. This trap occurs when someone decides to write a template engine with &#8220;a simple syntax that designers can understand&#8221; &#8211; it starts with some includes and printing a variable here and there. All goes well until he realizes he needs looping, so he builds loops into the language. And so it continues until the template engine is as complicated as any other programming language.<span id="more-1534"></span></p>
<p>This is probably the most common argument against template engines. People often say &#8220;but PHP IS a template engine&#8221;. Proponents of template engines will then counter argue that the syntax is simpler, but in some cases this is just not true&#8230;</p>
<p>We use Smarty in one of our products and in retrospect, we would most likely not have chosen to use it if we had to do it all again. However, based on our requirements and design decisions at the time, it was probably the right choice for then. When we started out, we opted for a MVC architecture where controllers pull data from models and push the data as arrays to the view. The advantage of this approach is that it keeps the templates simple because you&#8217;re only ever printing the contents of variables and occasionally looping over a dataset.</p>
<p>As our product evolved and became more complicated, this process became tedious and inefficient. Objects had to be converted to arrays and passed to the view. Sometimes this included a hierarchy of child objects. Then we started implementing lazy loading and iterators, the benefit of which quickly evaporated when we converted all of our objects to arrays.</p>
<p>We decided to instead pass either the model objects to the view or to use view helpers. The view then calls methods on the model or loops over the iterator, preserving the original objects and any lazy loading. All was well again, but of course the views started getting more and more complicated. To refer back to the argument, our templates have now become as complicated as embedded PHP code in HTML would have been. Add of course the additional overhead of the template engine and the cost of learning yet another language and suddenly a template engine doesn&#8217;t make an awful lot of sense anymore.</p>
<p>The problem is that requirements, design decisions and technologies all shift and evolve over time. It is not possible to predict where your product will be in 2 years, 5 years or even a few months from now. As software engineers, we try to accommodate change as much as possible by building safeguards into our code. However, at the end of the day, we cannot predict the future so we have to make peace with the fact that continuous re-factoring is as much a fact of life as change itself.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2010/08/02/the-smarty-trap/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>php&#124;tek 2010: A conference for beginners and veterans</title>
		<link>http://www.mihswat.com/2010/06/09/phptek-2010-a-conference-for-beginners-and-veterans/</link>
		<comments>http://www.mihswat.com/2010/06/09/phptek-2010-a-conference-for-beginners-and-veterans/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 12:46:17 +0000</pubDate>
		<dc:creator>Rafael Dohms</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[phptek]]></category>
		<category><![CDATA[tekx]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=1358</guid>
		<description><![CDATA[Tek has a reputation of being one of the most community-centered conferences, and true to its reputation this year’s conference promoted a variety of social networking activities alongside the usual conference sessions <a href="http://www.mihswat.com/2010/06/09/phptek-2010-a-conference-for-beginners-and-veterans/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Once again php|architect hosted the <a href="http://tek.phparch.com/">php|tek</a> conference, a yearly event held in Chicago. Tek has a reputation of being one of the most community-centered conferences, and true to its reputation this year’s conference promoted a variety of social networking activities alongside the usual conference sessions. The presence of various key players in the PHP ecosystem (Core Developers, Community Leaders, Products leaders and various representatives and evangelists from leading companies) was definitively a highlight for me.<span id="more-1358"></span></p>
<p>The sessions catered for all levels of developers, from basic introductions to advanced and incredibly engaging workshops. Sessions that stood out for me included anti-gaming techniques, in depth looks at the PHP Core, scaling, new technologies like git and xmpp, amongst others.</p>
<p>php|tek also provided a great opportunity for networking. From my personal experience (being a veteran PHP developer of over 10 years) this aspect of a conference can often be more important then the actual sessions. For a seasoned developer many sessions do not dwell deeply enough on advanced topics, serving more as a point of study initiation then as a full injection of knowledge. However the opportunity to meet developers of the very technologies you employ on a day to day basis enables far greater learnings. Simply because during these opportunities you can address your problems &#8211; be it by talking to the creator of the tool, or by talking to the developers of renown websites &#8211; during lunch, in the hallway or even during after-event  drinks.</p>
<p>Let’s take for example the opportunity of chatting with <a href="http://sebastian-bergmann.de">Sebastian Bergmann</a>, creator of <a href="http://www.phpunit.de/">PHPUnit</a>. Being able to discuss and resolve issues you have while implementing tests in your application, learning from him how you can automate your environment and implement more QA processes. Or engaging with <a href="http://weierophinney.net/matthew/">Matthew Weier O’Phinney</a>, lead of the <a href="http://framework.zend.com/">Zend Framework</a> project to learn how to participate in bug hunting &#8211; solving a bug you have found right there on the spot.</p>
<p>Imagine how much you can learn from talking with someone like <a href="http://eliw.com">Eli White</a>, former developer of <a href="http://digg.com">Digg</a>, getting scaling tips tailored to your scenario directly from someone who has had the opportunity to deal with high traffic and site availability. Or chatting to people like <a href="http://www.lornajane.net/">Lorna Jane Mitchell</a> and <a href="http://www.dragonbe.com/">Michelangelo van Dam</a> &#8211; people who have built their careers on contributing to the community. Leaders like these have helped developers to better qualifications and consequently projected their own names into the halls of fame of the ecosystem, opening doors to new opportunities and places. Career advice from such people would prove to be a turning point in any developers life.</p>
<p>All of this is possible and very welcome during the week that everyone is gathered at php|tek. In fact, even before the conference  started I was already  taking advantage of the great minds around me! Having arrived a couple days before the event and still having work to catch up on (for the official release of my latest project <a href="http://sharemymap.com">Share My Map</a>), I decided to head down to the lobby to code. To my surprise many of the speakers were there doing the same thing! So I had the opportunity of coding, surrounded by many of the creators of the tools I was using. Needless to say this was amazing &#8211; I was able to instantly get opinions on what I was working on &#8211; from world-leading experts all very eager to show me alternatives to the code I was writing and provide explanations to the up or downsides of the code in question.</p>
<p>The networking aspect of a coder’s career are often overlooked but  in my opinion this is a vital part of a successful professional life. Your network can make a difference in many different stages of you career and industry events like php|tek are important opportunities to meet and engage with industry leaders. I certainly made the most of my time at php|tek &#8211; let me know what your best moments were&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2010/06/09/phptek-2010-a-conference-for-beginners-and-veterans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Microsoft Web Developer Summit 2009</title>
		<link>http://www.mihswat.com/2009/12/21/microsoft-web-developer-summit-2009/</link>
		<comments>http://www.mihswat.com/2009/12/21/microsoft-web-developer-summit-2009/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 11:50:05 +0000</pubDate>
		<dc:creator>Rafael Dohms</dc:creator>
				<category><![CDATA[microsoft]]></category>
		<category><![CDATA[Microsoft Web Developer Summit]]></category>
		<category><![CDATA[mwds]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=1018</guid>
		<description><![CDATA[This year I was honored by being invited to participate as a member of the PHP Community in Microsoft&#8217;s Web Developer Summit. I used the opportunity to represent the huge PHP community in Brazil and highlight the community&#8217;s work. Let &#8230; <a href="http://www.mihswat.com/2009/12/21/microsoft-web-developer-summit-2009/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This year I was honored by being invited to participate as a member of the PHP Community in Microsoft&#8217;s Web Developer Summit. I used the opportunity to represent the huge PHP community in Brazil and highlight the community&#8217;s work.<span id="more-1018"></span></p>
<p>Let me give you a glimpse of what the event tries to accomplish and tell you what came out of it in 2009. MSWDS is all about communication. It is a yearly event that allows Microsoft to get in touch with key players in the PHP community and interact with them on various levels. This means they get to ask us questions, and we rant and ask them questions. It is a an effective way of getting Microsoft and PHP to do better business together, which in turn means getting better tools and better performing PHP applications on Microsoft platforms. Both sides get to know more about how the other operates.</p>
<p>Over 3 days Microsoft and the PHP community shared notes, discussed various products and opinions and shared quite a few beers and dinners at the Redmond Commons Campus.</p>
<p><strong>Microsoft has been very active in the PHP area</strong> and even though this is often received with skepticism by the overall community their actions are generating a lot of benefits for the PHP community specifically and Windows users in general. You cannot be right all the time, so Microsoft is still making some mistakes, but it is worth looking at some of what they shared with us. The final day of the conference was held under a non-disclosure agreement and is therefore not included here.</p>
<p>One of the highlights of the event was a project led by <a href="http://blogs.msdn.com/garretts/">Garrett Serrack</a> describing the process and plans for making PHP and associated libraries easier to compile from source on Windows &#8211; a project that could give Windows a push as a viable platform for PHP, since custom PHP compilations are a big part of PHP sites. Also very interesting were the news of WebPI and IIS. IIS is working on being a centralized dashboard for system developers and administrators and new tools like the SEO toolkit are laying down a new track for innovation. The road ahead for this is still long, but Microsoft got a lot of feedback on the kind of deploy and maintenance oriented services we developers would like to see such as imporvements to WinCache to offer more features and make it share the spotlight with <a href="http://php.net/manual/en/book.apc.php">APC</a>.</p>
<p>The WebPI project made life for PHP application users a breeze &#8211; its simplicity and the application gallery makes it very simple to install a complete web platform and get a site up and running. The same is not true for developers. Solutions were gathered to address developer needs &#8211; amongst these are multiple side-by-side versions of PHP and other applications, automated testing and closed cycle solutions that can contribute back to our applications as well as make our life deploying and testing before releases much easier on this platform.</p>
<p>During our <em><strong>airing of grievances</strong></em> many topics came up which Microsoft really needs to address. The long lead time to new projects and solutions and all the bureaucratic red tape that needs to be cut was the starting point and showed Microsoft they are the ones slowing themselves down. We also highlighted the areas of the world that need more attention from Microsoft evangelists. Recurring topics such as drivers for SQL Server and better developer tools for IE7 and IE8 came up as well.</p>
<p>One matter that generated heated arguments was the <a href="http://www.codeplex.org/"><em>Codeplex Foundation</em></a>. The discussion was triggered by ill-timed and not unplanned comments of an &#8220;<em>info-mercial like</em>&#8221; nature. Unfortunately Microsoft is still a huge corporation and parts of it still does not understand that the developer community does not want marketing pitches. The message hit home and some sessions reverted from that format, but the Codeplex idea was still not palatable tomost of the people present. The topic was later brought up in a round-table discussion and disagreements were addressed, showing that Microsoft is willing to correct some mistakes.</p>
<p>Some sessions had .NET solutions at their heart and were not very effective in communication, some were interesting enough to generate in us the desire to <em>copy</em> them, but in my opinion these were not really in their right place for the objective of this event. New technologies such as  PowerShell, Azure and Silverlight got lots of attention and showed some in the room that these could be much more useful than they thought it could be.</p>
<p>Silverlight triggered further discussion with its use in Bing Maps &#8211; the latter is now live with very striking visual effects. Microsoft&#8217;s skill for naming projects was criticised many times especially after we figured out that the &#8220;ASP.NET Ajax Toolkit&#8221; was an ajax library that had nothing to do with ASP.NET. This was dully noted by MS for future naming.</p>
<p>Microsoft also had an opportunity to listen to the main players in the PHP community about the community itself, <a href="http://benramsey.com/">Ramsey</a> went over some concepts of user groups and I talked about the new organization of user groups in Brazil (<a href="http://www.slideshare.net/rdohms/php-community-in-brazil">simple slides</a>). We also had sessions by <a href="http://blog.tabini.ca/">Marco</a> and <a href="http://caseysoftware.com/">Keith</a> on uncons and community participation, as well as a few sessions on tools and frameworks/closed apps.</p>
<p>One of the sessions explained how we can get in touch with Microsoft and gave us some insight on the internal structure and roles of all Microsoft related posts. This session was great and also opened the floor to questions from both sides.</p>
<p>The end result of the summit was very positive, even though we may only start seeing concrete results in a few months or even a year. The important message i got out of the conference is that Microsoft is working hard on matching Linux as a viable deploy platform and development platform, but more than that they are looking to go one better and innovate. Investing in professionals that develop PHP and its related libraries is also a way that Microsoft can help PHP to be even more viable on Windows. I guess it is becoming more viable and you should give it a try.</p>
<p>I look forward to some of the new tools and features of current products that were showcased in open and closed sessions &#8211; I believe Microsoft has a chance of doing great things for the PHP community.</p>
<p>For the team that organised MSWDS all I can say is that you did more then an awesome job: the hotel was great, social events were a great opportunity to get into more detailed talks about the day&#8217;s topics. The whole event went down without a glitch &#8211; thank you very much for all the hard work.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2009/12/21/microsoft-web-developer-summit-2009/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ZendCon 2009 PHP Conference &#8211; Review</title>
		<link>http://www.mihswat.com/2009/11/11/zendcon-2009-php-conference-review/</link>
		<comments>http://www.mihswat.com/2009/11/11/zendcon-2009-php-conference-review/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 13:55:15 +0000</pubDate>
		<dc:creator>Neil Broers</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[zendcon]]></category>
		<category><![CDATA[zendcon09]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=1000</guid>
		<description><![CDATA[October 2009 saw my return to San Jose for one of the top conferences on the PHP calendar - ZendCon. <a href="http://www.mihswat.com/2009/11/11/zendcon-2009-php-conference-review/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>October 2009 saw my return to San Jose for one of the top conferences on the PHP calendar &#8211; ZendCon. Other than taking place a month later and the conference venue shifting locations slightly, much of the format of this year&#8217;s ZendCon was the same as last year&#8217;s.<span id="more-1000"></span></p>
<p>Taking the organizational reigns this time around, Eli White takes over from Cal Evans who recently moved from Zend to iBuildings. Organization was mostly smooth, with a few minor hiccups &#8211; day 1 had a serious lack of power supply, leaving most attendees with dying laptops before lunch. Compounding the problem, no notepads or pens were provided on registration. Attendees who had registered early and received free netbooks reported that the netbooks came with European plugs instead of US ones. However, most of these issues were sorted out by day 2.</p>
<p>The speakers at this year&#8217;s ZendCon included some familiar stalwarts &#8211; Sebastian Bergmann was back and presented on topics including testing, quality assurance and continuous integration. Accompanying him, was Stefan Priebsch and Arne Blankerts, who together with Sebastian Bergmann makes up the newly formed PHP consulting company, thePHP.cc. Cal Evans was present in the capacity as a speaker and delivered a good presentation on design patterns. Of course,  Elizabeth Marie Smith was back and presented on PHP for the desktop using php GTk as well as a talk on SPL</p>
<p>Of all the speakers, two that stood out was Ilia Alshanetsky and Stefan Priebsch. I attended two of Ilia sessions, the first about premature optimization and the second on popular caching tools, APC and Memcache. His rapid delivery style and excellent knowledge crammed an almost overwhelming amount of content into a single one hour slot. Stefan Priebsch joined in on a code review tutorial session with Sebastian Bergmann and Arne Blankerts, but it was only when he presented on OOP best practices when he came into his own. Stefan is an engaging speaker and his OOP knowledge demands a lot of respect.</p>
<p>As usual, Twitter and the ZendCon IRC channel was abuzz with attendees tweeting during the conference and was a great way to keep a finger on the conference’s pulse.</p>
<p>The conference, however, wasn&#8217;t without negatives &#8211; drinks (soft drinks and coffee) were only served after every 2 talks and physically removed after the break, even though these weren&#8217;t refrigerated to begin with. In some instances, I had to leave the conference venue to purchase my own drinks.</p>
<p>This year there was no party or any afterhours activities arranged by the conference or sponsors other than the usual reception &#8211; this year sponsored by Adobe.</p>
<p>Regarding the format of the conference, I do feel that there are too many talks and the talks are too short &#8211; it is simply not possible (unless your name is Ilia Alshanetsky) to fit any meaningful amount of information into a one hour slot , especially the more advanced topics (which are of course the more interesting ones).</p>
<p>ZendCon 09 ended with a framework shootout &#8211; a representative of each of the more popular PHP frameworks were invited to appear in a panel discussion and the audience grilled them with questions. Of course, to liven things up, each panel member was provided with a toy gun. Although not particularly useful, it was highly entertaining and a great way to end the conference with.</p>
<p>For a list of conference speakers, talks, ratings and slides of this year’s ZendCon, check out the <a title="ZendCon Joind.in page" href="http://joind.in/event/view/44">ZendCon Joind.in page</a>.</p>
<div style="overflow: hidden;width: 1px;height: 1px">
<p class="MsoNormal">ctober 2009 saw my return to San Jose for one of the top conferences on the PHP calendar &#8211; ZendCon. Other than taking place a month later and the conference venue shifting locations slightly, much of the format of this year&#8217;s ZendCon was the same as last year&#8217;s.</p>
<p class="MsoNormal">
<p class="MsoNormal">Taking the organizational reigns this time around, Eli White takes over from Cal Evans who recently moved from Zend to iBuildings. Organization was mostly smooth, with a few minor hiccups &#8211; day 1 had a serious lack of power supply, leaving most attendees with dying laptops before lunch. Compounding the problem, no notepads or pens were provided on registration. Attendees who had registered early and received free netbooks reported that the netbooks came with European plugs instead of US ones. However, most of these issues were sorted out by day 2.</p>
<p class="MsoNormal">
<p class="MsoNormal">The speakers at this year&#8217;s ZendCon included some familiar stalwarts &#8211; Sebastian Bergmann was back and presented on topics including testing, quality assurance and continuous integration. Accompanying him, was Stefan Priebsch and Arne Blankerts, who together with Sebastian Bergmann makes up the newly formed PHP consulting company, thePHP.cc. Cal Evans was present in the capacity as a speaker and delivered a good presentation on design patterns. Of course,  Elizabeth Marie Smith was back and presented on PHP for the desktop using php GTk as well as a talk on SPL.</p>
<p class="MsoNormal">
<p class="MsoNormal">Of all the speakers, two that stood out was Ilia Alshanetsky and Stefan Priebsch. I attended two of Ilia sessions, the first about premature optimization and the second on popular caching tools, APC and memcache. His rapid delivery style and excellent knowledge crammed an almost overwhelming amount of content into a single one hour slot. Stefan Priebsch joined in on a code review tutorial session with Sebastian Bergmann and Arne Blankerts, but it was only when he presented on OOP best practices when he came into his own. Stefan is an engaging speaker and his OOP knowledge demands a lot of respect.</p>
<p class="MsoNormal">
<p class="MsoNormal">As usual, Twitter and the ZendCon IRC channel was abuzz with attendees tweeting during the conference and was a great way to keep a finger on the conference’s pulse.</p>
<p class="MsoNormal">
<p class="MsoNormal">The conference, however, wasn&#8217;t without negatives &#8211; drinks (soft drinks and coffee) were only served after every 2 talks and physically removed after the break, even though these weren&#8217;t refrigerated to begin with. In some instances, I had to leave the conference venue to purchase my own drinks.</p>
<p class="MsoNormal">
<p class="MsoNormal">This year there was no party or any afterhours activities arranged by the conference or sponsors other than the usual reception &#8211; this year sponsored by Adobe.</p>
<p class="MsoNormal">
<p class="MsoNormal">Regarding the format of the conference, I do feel that there are too many talks and the talks are too short &#8211; it is simply not possible (unless your name is Ilia Alshanetsky) to fit any meaningful amount of information into a one hour slot , especially the more advanced topics (which are of course the more interesting ones).</p>
<p class="MsoNormal">
<p class="MsoNormal">ZendCon 09 ended with a framework shootout &#8211; a representative of each of the more popular PHP frameworks were invited to appear in a panel discussion and the audience grilled them with questions. Of course, to liven things up, each panel member was provided with a toy gun. Although not particularly useful, it was highly entertaining and a great way to end the conference with.</p>
<p class="MsoNormal">
<p class="MsoNormal">For a list of conference speakers, talks, ratings and slides of this year’s ZendCon, check out the ZendCon Joind.in page: <a href="http://joind.in/event/view/44">http://joind.in/event/view/44</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2009/11/11/zendcon-2009-php-conference-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Iterating with SPL 101: Directory Iterators</title>
		<link>http://www.mihswat.com/2009/10/06/iterating-with-spl-101-directory-iterators/</link>
		<comments>http://www.mihswat.com/2009/10/06/iterating-with-spl-101-directory-iterators/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 09:47:07 +0000</pubDate>
		<dc:creator>Rafael Dohms</dc:creator>
				<category><![CDATA[examples]]></category>
		<category><![CDATA[iterators]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[spl]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=858</guid>
		<description><![CDATA[In the past I blogged about SPL (the Standard PHP Library) and how it makes PHP Developers&#8217; life&#8217;s easier. Since then i have noticed a lack of SPL recipes on the web. If you are getting to know SPL, the &#8230; <a href="http://www.mihswat.com/2009/10/06/iterating-with-spl-101-directory-iterators/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In the past I blogged about SPL (the Standard PHP Library) and how it makes PHP Developers&#8217; life&#8217;s easier. Since then i have noticed a lack of SPL <em>recipes</em> on the web. If you are getting to know SPL, the use of the available classes can be a real mystery. So I decided to add more posts on SPL for Google to add to its index. This is the first in a series of posts.<span id="more-858"></span></p>
<p>Wouldn&#8217;t it be nice if you could live life just by applying a <strong>foreach</strong> to each year and live day by day? Ok, that was an awful joke, but using iterators does make life a lot easier and it makes for cleaner code. SPL&#8217;s iterator classes are really awesome and helpful &#8211; they replace multiple lines of code and a handful functions with a simple <strong>new</strong>. This and a <strong>foreach</strong> can really help cleaning up code. Admittedly there is an argument that this might make the code less legible to &#8220;beginner&#8221;programmers or programmers that are not familiar with iterators and such, but hey, if you can&#8217;t understand it, read this post and learn it.</p>
<p>In this article i want to go over some of SPL&#8217;s Directory Iteration options, following up with more details on the code i posted in the original SPL article. Let&#8217;s dive into the infinity of iterators and iterate over them, showing how they &#8220;go together&#8221;and where to get them to solve things for you.</p>
<h2>Native in SPL</h2>
<p>Native SPL classes have been converted to C, so they perform much faster and are available in any PHP installation, especially since in PHP 5.3 you cannot disable SPL anymore.</p>
<h3>DirectoryIterator (<a href="http://www.php.net/~helly/php/ext/spl/classDirectoryIterator.html">doc</a>)</h3>
<p>This is a simple iterator because it is not recursive (so you don&#8217;t end up as dizzy as we did after the &#8220;Iteratah drinking game&#8221; at Tek&#8217;09). It basically replaces the functionality of the scandir function, but gives you a few more advantages along the way. You can pass it the directory you wish to iterate and it will return an object that you can foreach over as if it were an array. This is a simple task that can be done using scandir as well, so let&#8217;s compare advantages, starting with some code:</p>
<pre class="brush: php; title: ;">&amp;lt;php

echo '- Iterate diretory using scandir' . PHP_EOL;
echo '- Avoid DOT directories' . PHP_EOL;
echo '- Show full path' . PHP_EOL;
$dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree';
$files = scandir( $dir );
foreach($files as $file){
    if ($file != '.' || $file != '..'){
        echo $dir . DIRECTORY_SEPARATOR . $file . PHP_EOL;
    }
}
?&amp;gt;</pre>
<p>And same thing with DirectoryIterator</p>
<pre>&lt;php

echo '- Iterate directory using DirectoryIterator' . PHP_EOL;
echo '- Avoid DOT directories' . PHP_EOL;
echo '- Show full path' . PHP_EOL;
$files = new DirectoryIterator('samples' . DIRECTORY_SEPARATOR . 'sampledirtree');
foreach($files as $file){
    if (!$file-&gt;isDot()){
        echo $file-&gt;getRealPath() . PHP_EOL;
    }
}

?&gt;</pre>
<p>Output for both:</p>
<pre>- Iterate directory using (scandir|DirectoryIterator)
- Avoid DOT directories
- Show full path
samples/sampledirtree/file1.txt
samples/sampledirtree/folder1
samples/sampledirtree/folder2</pre>
<p>The code looks pretty much the same and we are basically performing a simple task, but one of the powerful built-in things about the DirectoryIterator is that instead of returning a string as scandir does, it returns a SplFileInfo Object, packed with a lot of information goodness. It allows us to skip the &#8220;dot&#8221; files ( . and .. ) without testing for both, and it allows us to get a file&#8217;s full real path without having to concatenate the actual directory. It does even more, check out the main methods list: (<a href="http://www.php.net/~helly/php/ext/spl/classSplFileInfo.html">whole list</a>)</p>
<ul>
<li>getFilename ()</li>
<li>getOwner ()</li>
<li>getPath ()</li>
<li>getPathname ()</li>
<li>getPerms ()</li>
<li>getRealPath ()</li>
<li>getSize ()</li>
<li>getType ()</li>
<li>isDir ()</li>
<li>isExecutable ()</li>
<li>isFile ()</li>
<li>isLink ()</li>
<li>isReadable ()</li>
<li>isWritable ()</li>
<li>openFile ($mode= &#8216;r&#8217;, $use_include_path=false, $context=NULL)</li>
</ul>
<p>Arguably one can also get this information by calling a function, but hey &#8211; this is OO. It is cleaner and not procedural. So it makes for much cleaner code and ease of use because you have a fully qualified object to handle a file right there, just a method call away. Its important to note that this does come at a performance cost, but at less then 40% and measured in much less then microseconds, this is not a major thing to worry about.</p>
<h3>RecursiveDirectoryIterator (<a href="http://www.php.net/~helly/php/ext/spl/classRecursiveDirectoryIterator.html">doc</a>)</h3>
<p>This is where the fun begins, recursive goodness. You probably noticed above that the script did not follow up on the folders it found, it stayed within the first level of the directory we chose. Recursion solves this problem. Basically this iterator will go into directories, executing <strong>DirectoryIterator</strong> on anything that is a directory. This is done by implementing the <strong>getChildren</strong> function which allows you to get a <strong>DirectoryIterator</strong> instance of the child directory.</p>
<p>Using the regular <strong>scandir</strong> approach we would have had to use a recursive function to obtain this behavior, but using this we only need to.. <em>&#8220;wait, even with the <strong>getChildren</strong> function we still would need a recursive function to go through it, hey! someone lied to me!&#8221;</em> .. This is where SPL composite magic comes in, we simply need to use a <strong>RecursiveIteratorIterator</strong> (see how the drinking game begins to be fun?).</p>
<p>The <strong>RecursiveIteratorIterator</strong> is basically an object that implements the recursive function, but without the complications. Just pass a <strong>Recursive<em>&lt;whatever&gt;</em>Iterator</strong> to its construct and <strong>foreach</strong> away. The iterator will automatically call the <strong>getChildren</strong> functions and manage that, and you can even tell it how to behave.</p>
<pre>&lt;php

function recursiveScanDir($dir){
    $files = scandir($dir);
    foreach($files as $file){
        if ($file != '.' &amp;&amp; $file != '..'){
            if (is_dir($dir . DIRECTORY_SEPARATOR . $file)){
                recursiveScanDir($dir . DIRECTORY_SEPARATOR . $file);
            }else{
                echo $dir . DIRECTORY_SEPARATOR . $file . PHP_EOL;
            }
        }
    }
}

$dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree';
recursiveScanDir($dir);

?&gt;</pre>
<p>Now using SPL stuff with 3.5 less lines of code:</p>
<pre>&lt;php

$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator('samples' . DIRECTORY_SEPARATOR . 'sampledirtree') );
foreach($files as $file){
    echo $file-&gt;getPathname() . PHP_EOL;
}

?&gt;</pre>
<p>Output:</p>
<pre>samples/sampledirtree/file1.txt
samples/sampledirtree/folder1/file1.txt
samples/sampledirtree/folder1/file2.html
samples/sampledirtree/folder2/file1.html
samples/sampledirtree/folder2/file2.txt</pre>
<p>We used default settings here, but by manipulating the <strong>$mode</strong> property of the contract (2nd parameter), we can for example show children first, or &#8220;leaves&#8221; only. If you are not seeing it yet, imagine that you want to remove a directory structure &#8211; you can&#8217;t just use <strong>rmdir</strong> because it will fail due to files existing inside the folder. So you will need to delete all the files one by one,  following the folder hierarchy. If you use this iterator combination and ask it to show children first, you can then delete all children and afterward remove the parents, like in this code:</p>
<pre>&lt;php
//Recursively delete tree structure
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('samples' . DIRECTORY_SEPARATOR . 'sampledirtree'), RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file){
    if ($file-&gt;isDir()){
        rmdir($file-&gt;getRealPath());
    }else{
        unlink($file-&gt;getRealPath());
    }
}
?&gt;</pre>
<p>You might not see the advantage of SPL over <strong>scandir</strong> in the basic stuff, but once you start adding operations to your iteration and start to need specific behavior, you begin to realize it let&#8217;s you have much simpler and easily readable code, plus its OO! (i&#8217;m a big OO fan BTW)</p>
<h2>Non-native in SPL</h2>
<p>Non-native SPL clases are available currently as examples and some will be converted to C and integrated in the native part of SPL. Some contain useful as examples and you can implement them locally for your own use, or you can load these examples into your code by one of two methods:</p>
<ul>
<li>Add <em>ext/spl/examples/autoload.inc</em> to you php.ini in auto_prepend_file (or add it to the file already set in auto_prepend_file)</li>
<li>Include <em>ext/spl/examples/autoload.inc</em> in your application</li>
</ul>
<p>The <em>autoload.inc</em> file is available in the folder above, which should be in your PHP install or in the source code you can download from PHP.net. I would recommend downloading this and adding it into your application tree if you wish to use it.</p>
<p><em><strong>Personal Recommendation:</strong> Use everything in the examples folder as inspiration to what you can do with SPL and implement it locally</em></p>
<h3>DirectoryTreeIterator (<a href="http://www.php.net/~helly/php/ext/spl/classDirectoryTreeIterator.html">doc</a>)</h3>
<p>The <strong>DirectoryTreeIterator</strong> is more interesting as an example of what you can do with the iterators as to actually be something you might use on a daily basis. It does what the <strong>RecursiveDirectoryIterator</strong> does but diplays the result as a ASCII directory tree, so using this code:</p>
<pre>&lt;php
set_include_path( get_include_path() . PATH_SEPARATOR . 'spl' . DIRECTORY_SEPARATOR . 'examples' );
include('spl' . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . 'autoload.inc');

$files = new DirectoryTreeIterator('samples' . DIRECTORY_SEPARATOR . 'sampledirtree');

foreach($files as $file){
    echo $file . PHP_EOL;
}

?&gt;</pre>
<p>We get this result:</p>
<pre>|-samples/sampledirtree/file1.txt
|-samples/sampledirtree/folder1
| |-samples/sampledirtree/folder1/file1.txt
| \-samples/sampledirtree/folder1/file2.html
\-samples/sampledirtree/folder2
  |-samples/sampledirtree/folder2/file1.html
  \-samples/sampledirtree/folder2/file2.txt</pre>
<p>Since i said its more interesting as an example, let&#8217;s look at the actual source code of the class that does the printing:</p>
<pre>	function current()
{
$tree = '';
for ($l=0; $l &lt; $this-&gt;getDepth(); $l++) {
$tree .= $this-&gt;getSubIterator($l)-&gt;hasNext() ? '| ' : '  ';
}
return $tree . ($this-&gt;getSubIterator($l)-&gt;hasNext() ? '|-' : '\-')
. $this-&gt;getSubIterator($l)-&gt;__toString();
}</pre>
<p>As you can see, it is just a matter of working the ASCII to images and css and you can very easily have a directory tree anywhere on your site, by taking advantage of the <strong>RecursiveDirectoryIterator</strong>.</p>
<h1>End of Part I&#8230;</h1>
<p>This is a brief overview of what you can do with all the Directory Iterators available in SPL. Combining these directory iterators with other navigation iterators lets you do a lot more. This will be the topic of another post in which I will talk about all the different iterators you can use to iterate over iterators (say that 3x fast!) all the way from the FilterIterator to the InfinityIterator. I hope this helps you to get an idea of how to make your code better with SPL code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2009/10/06/iterating-with-spl-101-directory-iterators/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Security: Are you thinking about it?</title>
		<link>http://www.mihswat.com/2009/10/01/security-are-you-thinking-about-it/</link>
		<comments>http://www.mihswat.com/2009/10/01/security-are-you-thinking-about-it/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 10:13:46 +0000</pubDate>
		<dc:creator>Rafael Dohms</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Project Management]]></category>
		<category><![CDATA[development cycle]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[teams]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=823</guid>
		<description><![CDATA[Security is a recurring topic when discussing Technology. Taking security for granted when you are developing an application, even if it is a very simple application is a huge mistake which can have grave consequences. I have ran into many &#8230; <a href="http://www.mihswat.com/2009/10/01/security-are-you-thinking-about-it/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Security is a recurring topic when discussing Technology. Taking security for granted when you are developing an application, even if it is a very simple application is a huge mistake which can have grave consequences. <span id="more-823"></span><br />
I have ran into many excuses for ignoring security &#8211; especially this one: &#8220;This is just a simple application, it has no sensitive data&#8221;. The point may seem valid to the developer who is under immense time pressure, but the consequences of neglecting security can be serious. <a href="http://blog.calevans.com/2009/08/27/will-speak-for-cab-fare/">Cal Evans</a> in his Open Teams session demonstrates the impact of deadlines when he tells us about a project with an impossible due date. Upon questioning the due date to the marketing department their reply was simple: &#8220;Because that&#8217;s when the brochures are done&#8221;. This demonstrates the  all too frequent lack of understanding of the complexity of issues around web development shown by the business side of organisations.</p>
<p>Whatever the reason for neglecting security may be, such neglect can compromise much more than just the &#8220;non-sensitive&#8221; application data. Consider for example a recent incident at one of the biggest Brazilian mobile companies. An issue was found in a file called popup.php. The code in the file had the apparently simple objective of appending the company logo and loading a given file&#8217;s content into a popup window. So the excuse of &#8220;non-sensitive&#8221; data seemed to apply in this case.</p>
<p>We can easily imagine that the need for this page probably originated in the &lt;insert non-tech department&gt; and got escalated to the tech department with high priority (late on a Friday afternoon). In the rush the priority was to &#8220;Just get it done&#8221;, and ignore the worries about security. &#8220;No problem&#8221; you say, &#8220;leave it like that during the weekend and redo it on Monday following the proper protocols&#8221;. What happens of course is that code is never looked at again&#8230;.until the day THE EPIC FAIL happens.</p>
<p>In retrospect we can easily see how the popup.php file led to THE EPIC FAIL. The final URL used by the popup.php file had a &#8220;url&#8221; GET var attached to it, the value of which usually pointed to another html or PHP file. This is an open invitation to try and point the GET to any file that would be &#8220;unexpected&#8221;, like so:</p>
<p><a href="http://www.mihswat.com/wp-content/uploads/2009/09/url2.jpg"><img class="alignnone size-medium wp-image-824" src="http://www.mihswat.com/wp-content/uploads/2009/09/url2-300x22.jpg" alt="Url" width="300" height="22" /></a></p>
<p>The result of this request immediately made obvious that at least 2 security issues were overlooked by the developer. Can you see which ones?</p>
<p><a href="http://www.mihswat.com/wp-content/uploads/2009/09/erro.jpg"><img class="alignnone size-medium wp-image-825" style="border: 1px solid black" src="http://www.mihswat.com/wp-content/uploads/2009/09/erro-300x58.jpg" alt="Error" width="300" height="58" /></a></p>
<p>The first mistake here was leaving display_errors on &#8211; and this shows us the second mistake(s).  The obvious one was neglecting to stick to the rule: &#8220;Filter input, escape output&#8221;. The developer obviously  actually executed an include on the file specified in the URL. We can see that he did not check in any way the value provided in the &#8220;url&#8221; parameter, but he should at least have checked whehther the file was still in the site&#8217;s file tree.</p>
<p>To turn this exploit into something dangerous you simply need to start passing it sensitive files, like /etc/passwd or try to load the apache httpd.conf file (which actually worked in this case).</p>
<p><a href="http://www.mihswat.com/wp-content/uploads/2009/09/passwd.jpg"><img class="alignnone size-medium wp-image-826" style="border: 1px solid black" src="http://www.mihswat.com/wp-content/uploads/2009/09/passwd-300x42.jpg" alt="passwd" width="300" height="42" /></a></p>
<p>Analyzing these files showed that the problem was severe. The actual site had little valuable information, but it did show that the server had much more on it than just this site &#8211; this qualifies as an EPIC FAIL because it compromised all systems on that server. Another factor that contributed to the severity of the problem was Twitter. This flaw was only fixed <em>2 days after it was first reported</em> and in the interval the detail of the exploit was widely circulated on Twitter, giving everyone the chance to look at configuration and other files. Only the victim knows if any sensitive data was compromised, but given the creativity of hackers nowadays, something was compromised for sure.</p>
<p>This demonstrates that security is not a simple &#8220;injection&#8221; or &#8220;pill&#8221; you can give your application after it is live &#8211; security needs to come from the ground up, leave the quick fixes for the occasional software bug. Your development cycle must include security concerns in the form of tests, validations or anything else you can think of. <a href="http://owasp.org">OWASP</a> is a great source of points to think about. No feature should roll out the door if it did not take security into consideration. One approach is to incorporate security into your &#8220;Definition of Done&#8221;, so that a task can only be complete after security steps are taken to validate it. Peer review can further contribute to enhanced security &#8211; two heads are better than one. Managers should be as worried about this as the programmers should be. An example of such a Definition of Done is:</p>
<ul>
<li>Developed</li>
<li>Tested (Unit Tests written and executed)</li>
<li>Documentation (proper doc file or PHPDoc blocks for code segments)</li>
<li>Peer review</li>
<li>Security check (for known flaws, like input filtering)</li>
<li>Load Testing</li>
</ul>
<p>Every task should include the above. Even though it may cost some project development time, it will save you even more time and effort if someone attempts to hack your site. Including security in the set of tasks gives the developer time to plan each feature and reduces the risk of exploits being released. Taking security into account is part of becoming a professional developer and leaving behind the code-hacker ethic which means just coding and not considering the environment in which the application exists. </p>
<p>Needless to say the security-conscious approach has to be embraced by management because it is usually up to them to fight the battle for more development time and proper development cycles, and not to simply give in to external pressures &#8211; which leads to the risk of distributing dangerous code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2009/10/01/security-are-you-thinking-about-it/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHPT: Writing tests for PHP</title>
		<link>http://www.mihswat.com/2009/09/01/phpt-writing-tests-for-php/</link>
		<comments>http://www.mihswat.com/2009/09/01/phpt-writing-tests-for-php/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 09:12:50 +0000</pubDate>
		<dc:creator>Rafael Dohms</dc:creator>
				<category><![CDATA[open source]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[phpt]]></category>
		<category><![CDATA[phptestfest]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=792</guid>
		<description><![CDATA[This year the PHP Community promoted the PHPTestFest in various places around the globe and it was a success. I participated in the event promoted by the PHPSP UG (PHP Sao Paulo User Group) which ended up as being the &#8230; <a href="http://www.mihswat.com/2009/09/01/phpt-writing-tests-for-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This year the PHP Community promoted the PHPTestFest in various places around the globe and it was a success. I participated in the event promoted by the PHPSP UG (PHP Sao Paulo User Group) which ended up as being the team with the most tests committed. After participating in the event I kept going and have since obtained an SVN account and karma to be an official test committer to PHP.<span id="more-792"></span> If you did not get the chance to learn how to write tests during your local TestFest, I will now go over the steps taken so you can be ready for next year. PHPT is an extremely simple test framework designed to test PHP itself. Its atomic nature and independent test execution makes it perfect for the kind of tests needed, so tests can be really focused on testing specific functions and/or bugs. <strong>What do I need to know?</strong> The beauty of PHPT is that you need to know very little other than how to write PHP code. A little knowledge of the inner workings of PHP will of course help you in finding areas of code that need testing, and how best to test them, but just knowing PHP is enough to start. I have divided this post into 5 parts:</p>
<ol>
<li>Preparing the Environment</li>
<li>Choosing what to test</li>
<li>Writing a test</li>
<li>Executing a test</li>
<li>Submitting a test to PHP</li>
</ol>
<p><!--more--></p>
<h2><strong>1. Preparing the Environment </strong></h2>
<p>Your test environment needs the correct version of PHP and the ability to run tests, I&#8217;m going to focus on *nix/MacOS systems here  as I have not had experience with tests on Windows. The first step is to compile PHP from source. During the testfest we focused on PHP 5.3, but you should head over to the PHP QA Page (<a href="http://qa.php.net/">qa.php.net</a>) to see what version is being targeted, or else take you pick from the PHP SVN. In any case &#8211; you need to download the source code that is appropriate for your system. The basic compilation process means you need to execute ./configure with your correct settings, and then run <em>make</em>. After running <em>make</em> you are already ready to run tests using the <em>make</em> test command. The latter will run all the current tests (9000+) and prompt you to send a report to the QA Team. But before you begin writing your own tests I recommend that you also run <em>make install</em> so you can have a proper PHP executable for the version you are testing. Later on we will see how to use <em>make test</em> to target only the tests you wish to execute.</p>
<h2><strong>2. Choosing what to test </strong></h2>
<p>Before you begin writing a test you must decide on what you are writing a test for. You will usually be either writing a test for a specific bug or to cover areas of PHP without &#8220;code coverage&#8221;. To figure out the bugs that have/need tests you should get on the QA mailing list or check out the correct path (for example for GD go to ext/gd/tests) for a filename with the bug-id. To write tests to cover untouched areas of the source code your best bet is to head over to <a href="http://gcov.php.net/">http://gcov.php.net</a> where you should pick you branch/version and look for the areas with less code coverage. In this year&#8217;s testfest the PHPSP group focused on the GD extension, so we where basically looking at the coverage for the gd.c file, which i will use for examples in this article. To decide what to test took a little bit of bit-scrubbing, so this is why I remarked earlier that knowing the inner working of PHP helps. However &#8211; after a few examples you will easily pick up what needs to be done.</p>
<p>Let&#8217;s start by analysing these lines of code from gd.c:</p>
<p><a href="http://www.mihswat.com/wp-content/uploads/2009/08/Picture-1.png"><img class="size-medium wp-image-798 alignnone" src="http://www.mihswat.com/wp-content/uploads/2009/08/Picture-1-300x68.png" alt="PHPT - C code" width="300" height="68" /></a></p>
<p>What we are looking for here are the red lines, which means that these lines were not executed. The main objective is to get all lines to either blue (executed) or white (non-executable code) as you can see above. The first thing you should notice here is that this is the code for the imageclorallocatealpha function as displayed online 1848 by the PHP_FUNCTION construct. Now you should look at the red lines where we can easily see that line 1856 is never executed, and judging by the IF construct before it we can state that this line is never executed because the zend_parse_parameters function (nevermind what it does for now) never returns the FAILURE state. As it happens, the zend_parse_parameters is responsible for parsing and validating the parameters passed to the function, so we can guess that this means that the current tests never pass an invalid parameter to the function, thus never testing if it actually returns a proper error message. This seems like  good place to begin learning about tests.</p>
<h2><strong>3. Writing a test </strong></h2>
<p>Writing the actual test is usually really simple, as it should be since tests need to be atomic. You should limit the scope of your test to testing only the function at hand and the particular situation you want to test &#8211; this will also help you name the test properly, as we will see next.</p>
<h3><strong>3.1 Naming test files </strong></h3>
<p>Naming test files is simple if you defined you scope correctly:</p>
<ul>
<li>Bug test: bug&lt;bugid&gt;.phpt</li>
<li>Basic function usage: &lt;função&gt;_basic.phpt</li>
<li>Function error behaviours: &lt;função&gt;_error.phpt</li>
<li>Variations of function usage: &lt;função&gt;_variation.phpt</li>
<li>Extensions: &lt;extensão&gt;_&lt;#&gt;.phpt</li>
</ul>
<h3><strong>3.2 Structure of a .phpt file </strong></h3>
<p>The simple structure of PHPT tests follows this basic pattern:</p>
<blockquote>
<pre>--TEST--
strtr() function - basic test for strstr()
--FILE--
/* Do not change this test it is a README.TESTING example. */
$trans = array("hello"=&gt;"hi", "hi"=&gt;"hello", "a"=&gt;"A", "world"=&gt;"planet");
var_dump(strtr("# hi all, I said hello world! #", $trans));
?&gt;
--EXPECT--
string(32) "# hello All, I sAid hi planet! #"</pre>
</blockquote>
<p>As we can see the &#8211;TEST&#8211; section holds a one-line title for the test and should make it pretty clear as to what is being tested. The &#8211;FILE&#8211; section is the actual test code which will be internally converted into a .php file and executed. And finally the &#8211;EXPECT&#8211; section will be compared to the .php output to see if they are the same, var_dump is recommended for the tests. These are just the most standard sections &#8211; the full documentation can be checked on the QA site under <a href="http://qa.php.net/phpt_details.php">phpt format,</a>. You will come across situations where these blocks are not sufficient, but generally you will be checking if function X is returning value Y when passed parameter Z, so the above is usually all you need. One block is very important namely the &#8211;CREDIT&#8211; block. Putting your name here is very important so you can be reached in case of problems, and also to ensure that you get credit for writing tests for PHP. We used this format in our testfest:</p>
<blockquote>
<pre>--CREDIT--
Rafael Dohms &lt;myemail@gmail.com&gt;
#PHPSPTestFest 2009-04-DD</pre>
</blockquote>
<p>Getting back to the code above, let&#8217;s try to write a test to cover the untested line we selected above. Let&#8217;s look closely at the parse function and figure out what we need to test:</p>
<blockquote>
<pre><span>zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, <strong>"rllll"</strong>, &amp;IM, &amp;red, &amp;green, &amp;blue, &amp;alpha)</span></pre>
</blockquote>
<p>The important part to look at is the <em>&#8220;rllll&#8221;</em> as it defines the type needed for each of the parameters. The first parameter for example requires a Resource as stated by the &#8220;r&#8221;, whereas the rest of them need Long value. If we look at the PHP manual for this function we will get:</p>
<blockquote>
<pre>int imagecolorallocatealpha ( resource $image , int $red , int $green , int $blue , int $alpha )</pre>
</blockquote>
<p>It confirms what we saw in the code, but it might also show wrong information, so this would be another point where you can help PHP updating and fixing the documentation. Let&#8217;s write a test to make sure that the function sends an error message if we pass something that is not a Resource as its first parameter. Looking inside the ext/gd/tests folder we do not find any imagecolorallocatealpha files, so according to the naming conventions above we should use the name <em>imagecolorallocatealpha_error1.phpt</em> for our test file, since we are checking error conditions and it is the first error test for this function. (in sequence we can user error2, error3&#8230; for the other parameters)</p>
<blockquote>
<pre>--TEST--
Testing imagecolorallocatealpha(): Wrong types for parameter 1
--CREDITS--
Rafael Dohms &lt;rdohms [at] gmail [dot] com&gt;</pre>
</blockquote>
<p>The first step is to get the test title right and tag it with our credit so we can be found in case of future changes or problems. Make sure your title describes the objective without being an essay.</p>
<blockquote>
<pre>--SKIPIF--
&lt;?php
    if (!extension_loaded("gd")) die("skip GD not present");
?&gt;</pre>
</blockquote>
<p>We did not mention the &#8211;SKIPIF&#8211; section before, but it is a key section in this case. This is very important because we are testing a function of the GD extension, so this means that depending on the local environment it might actually not be available, for example if GD is not enabled. In this case we do not want to execute these tests since they would all fail, leading to false negatives. This section can also be used for other skip criteria, like 32 bit Vs. 64 bit tests, or any other condition that you feel might affect your test. The section itself is very simple &#8211; just do a check and in case the conditions for skipping are met, call a die command and the test will be marked as SKIP not FAIL in the final execution.</p>
<blockquote>
<pre>--FILE--</pre>
<pre>&lt;?php $resource = tmpfile();

imagecolorallocatealpha($resource, 255, 255, 255, 50);
imagecolorallocatealpha('string', 255, 255, 255, 50);
imagecolorallocatealpha(array(), 255, 255, 255, 50);
imagecolorallocatealpha(null, 255, 255, 255, 50);
?&gt;</pre>
</blockquote>
<p>This is the body of the actual test &#8211; it is really simple and atomic. What we did is to call the function various times with different types of parameters. In the first call we are actually testing line 1859, because tmpfile returns a valid Resource, however not an Image Resource and line 1859 should catch that. The rest of the parameters receive valid values, in this case integers. Testing various types is interesting because you might find a specific type that causes non-expected behavior. Since we are hoping for error messages, we do not even need the return value of the function.</p>
<blockquote>
<pre>--EXPECTF--
Warning: imagecolorallocatealpha(): supplied resource is not a valid Image resource in %s on line %d</pre>
<pre>Warning: imagecolorallocatealpha() expects parameter 1 to be resource, %s given in %s on line %d</pre>
<pre>Warning: imagecolorallocatealpha() expects parameter 1 to be resource, array given in %s on line %d</pre>
<pre>Warning: imagecolorallocatealpha() expects parameter 1 to be resource, null given in %s on line %d</pre>
</blockquote>
<p>Finally we now have a &#8211;EXPECTF&#8211; block which is the same as a &#8211;EXPECT&#8211; block but uses a printf-like structure to skip out on dynamic parts of the test. As we can see strings such as file name or line are replaced by %s or %d meaning it will fit any value. This is important because different environments might return different file paths. You can also use blocks with regular expressions, but this format is much more simple and easy to read. As we can see we are expecting an error message for each of the calls we made. <em><strong> </strong></em></p>
<p><em><strong>Tip: </strong>To get these error messages, execute the phpt file using a php executable, like: php imagecolorallocatealpha_error1.phpt. The file will be executed and everything outside &lt;? tags will be output, and the actual output for the &#8211;FILE&#8211; block will be output as well, just copy-paste and replace dynamic bits.</em> <em><strong> </strong></em></p>
<p><em><strong>Tip 2:</strong> the error message usually states the given type, as in: string given; If you are expecting the string type in the error message, replace it with %s to make your test compatible with PHP 5.3- and PHP6, since in this case it would print &#8220;unicode string&#8221; instead of &#8220;string&#8221; </em></p>
<h2><strong>4. Executing a test </strong></h2>
<p>Your test is ready for the drill, now we need the drillmaster to pick it up and make it jump through the hoops. We have seen that <em>make test</em> executes the PHP tests, but with 9000+ tests this is too time consuming to test one new test. So we should get it to execute only our test and the related tests we need. To do this we can use the TESTS parameter which will define which tests should be executed:</p>
<blockquote>
<pre>make test TESTS=ext/gd/tests/imagecolorallocatealpha_*.phpt</pre>
</blockquote>
<p>You can either pass it the full path to your test or use a wildcard (*) to execute all tests that match the pattern &#8211; this is useful if we decided to write tests for all parameters and want to run them all at once. This is the resulting output:</p>
<p><a href="http://www.mihswat.com/wp-content/uploads/2009/08/Picture-2.png"><img class="alignnone size-medium wp-image-799" src="http://www.mihswat.com/wp-content/uploads/2009/08/Picture-2-300x142.png" alt="PHPT - Shell" width="300" height="142" /></a></p>
<p><a href="http://www.rafaeldohms.com.br/wp-content/uploads/Picture-2.png"></a> The test passes as we can see by the PASS text present before the test title (&#8211;TEST&#8211; block). Note that if this test had failed, the test framework would have created a few additional files to help you debug the problem. These files have the same name as the original .phpt but different extensions:</p>
<ul>
<li>.out &#8211; the output for the php code</li>
<li>.php &#8211; source code generated for the test (&#8211;FILE&#8211;)</li>
<li>.diff &#8211; a diff between &#8211;EXPECT&#8211; and the actual output</li>
<li>.exp &#8211; the isolated text in the &#8211;EXPECT&#8211; section</li>
<li>.log &#8211; a log of all information related (output, expected&#8230;)</li>
</ul>
<p>These files are extremely useful in debugging. They are auto-removed once you get the test to PASS.</p>
<h2><strong>5. Submitting you test to PHP </strong></h2>
<p>There are a few ways to get your test into the PHP SVN. The easiest one is to participate in a TestFest event. All tests written at these events are submitted to a separate repository and then migrated to the official repository. The second way is to send your test file to the QA mailing list (use pastebin) and get someone to review it. The final way is a mix of the previous ones, participate in a TestFest event.. get a taste for tests, write a whole bunch of them,  and at the end, apply for a SVN account. If you play your cards right and keep on writing tests you will easily get Karma and will become an official test committer in PHP.  Hey it happened to me, true story, so it just depends on you and your willingness to write tests.</p>
<h2><strong>Conclusion</strong></h2>
<p>Now htat you have all the tools you need, what are you waiting for? Go help out the PHP Community. But don&#8217;t stop there, get the taste for tests and bring them to your application as well using PHPUnit and TDD &#8211; which I hope to write more about soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2009/09/01/phpt-writing-tests-for-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Book Review: Guide to Date and Time Programming</title>
		<link>http://www.mihswat.com/2009/07/06/book-review-guide-to-date-and-time-programming/</link>
		<comments>http://www.mihswat.com/2009/07/06/book-review-guide-to-date-and-time-programming/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 09:37:33 +0000</pubDate>
		<dc:creator>Rafael Dohms</dc:creator>
				<category><![CDATA[book]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[derick rethans]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[review]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=736</guid>
		<description><![CDATA[This review has been pending for a while, but recently I finished reading Derick Rethans&#8217; book: Date and Time Programming. At first glance the topic of the book might lead you to think &#8220;why do I need a book to &#8230; <a href="http://www.mihswat.com/2009/07/06/book-review-guide-to-date-and-time-programming/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This review has been pending for a while, but recently I finished reading Derick Rethans&#8217; book:<em> Date and Time Programming</em>. At first glance the topic of the book might lead you to think &#8220;why do I need a book to teach me about such a simple topic&#8221; ? But further investigation and hard experience will show you that handling date and time in software development is not always as straightforward as &#8220;Its twelve o&#8217;clock&#8221;.<span id="more-736"></span> Derick&#8217;s book provides an in depth look at handling various aspects of date and time such as timezones and days that do not exist, and it delivers something that is missing from php.net: documentation for the DateTime Object.</p>
<p>The book covers a lot of ground, even though it looks rather thin. Derick does a wonderful job of introducing date/time matter in the opening chapter, covering all the calendar switches (Julian to Gregorian) and its complexities (did you know Feb 30th has already happened once?) as well as timezones, solar times and details of daylight-saving time. This is all invaluable information for anyone working with dates.</p>
<p>The remaining chapters delve into the various operations we use with and around date and time, like parsing, representing and manipulating date and time values. It directs attention to various features of the PHP functions that handles timezones and daylight savings. Its also very interesting that the book fully covers and makes crystal clear the new features in PHP 5.3 that pertains to this topic.</p>
<p>The book explores PHP internals and describes how to use timezones and to update the internal timezone database, as well as how to deal with database engines and still get back correctly timezoned dates.</p>
<p><em>Guide to Date and Time Programming</em> is a really pleasant read. In a very orderly fashion Derick covers all the steps before introducing new issues, instead of just raising issues without fully explaining what they are about. The book functions very well as reference book, since documentation on this topic is not all it should be in the PHP Manual. This is a <em>must-read</em> book for anyone that has ever had to deal with handling date or time in a PHP system, or anyone who plans on launching systems that are aware of timezone differences.</p>
<p><a href="http://www.rafaeldohms.com.br/wp-content/uploads/51w7jD2lpXL._SL500_AA240_.jpg"><img class="alignleft size-thumbnail wp-image-560" src="http://www.rafaeldohms.com.br/wp-content/uploads/51w7jD2lpXL._SL500_AA240_-150x150.jpg" style="float:left" alt="Date and Time" width="150" height="150" /></a></p>
<p><strong>php/architect&#8217;s Guide to Date and Time Programming</strong></p>
<p>by Derick Rethans</p>
<p>Paperback: 152 pages</p>
<p>Publisher: Marco Tabini &amp; Associates, Inc. (April 20, 2009)</p>
<p>Language: English</p>
<p>ISBN-10: 0981034500</p>
<p>ISBN-13: 978-0981034508</p>
<p>Available from <a href="http://www.amazon.com/architects-Guide-Date-Time-Programming/dp/0981034500/ref=sr_1_1?ie=UTF8&#038;s=books&#038;qid=1246873427&#038;sr=8-1">Amazon</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2009/07/06/book-review-guide-to-date-and-time-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SPL: The hidden gem</title>
		<link>http://www.mihswat.com/2009/06/08/spl-the-hidden-gem/</link>
		<comments>http://www.mihswat.com/2009/06/08/spl-the-hidden-gem/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 07:55:26 +0000</pubDate>
		<dc:creator>Rafael Dohms</dc:creator>
				<category><![CDATA[best practices]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[spl]]></category>

		<guid isPermaLink="false">http://www.mihswat.com/?p=724</guid>
		<description><![CDATA[By a show of hands, how many people here have ever heard of SPL? How many have used it? Chances are most of you did not raise your hands, and some might even have a confused look on their faces. &#8230; <a href="http://www.mihswat.com/2009/06/08/spl-the-hidden-gem/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>By a show of hands, how many people here have ever heard of SPL? How many have used it? Chances are most of you did not raise your hands, and some might even have a confused look on their faces. Not many know what SPL is, so let&#8217;s explore.<span id="more-724"></span></p>
<p>SPL, or <em>Standard PHP Library</em>, is a set of classes and interfaces that have been built in to PHP since version 5.0, and as of PHP 5.3 it cannot even be disabled, so it is here for good. Its actually hard to disable it when compiling, so 9.9 out of 10 times you can be sure that you have it. But why have you not used it? The answer begins with &#8220;poor documentation&#8221; and ends in &#8220;didn&#8217;t even know it existed&#8221;. SPL has not had the promotion that it deserves &#8211; but this article hopes to remedy that! So what is in SPL?</p>
<p>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 stuff 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?</p>
<p><strong>Overloading autoloader</strong></p>
<p>You are a by the book programmer, and after __autoload came around you rewrote all your sites and removed the endless stream os <em>includes</em> and <em>requires</em> in your code to make way for lazy loading, right? So once in a while you found yourself in a jam, your product&#8217;s classes use a specific naming/directory structure and the Zend Framework classes you use have a &#8220;_&#8221; to path approach, how do you solve this? Giant __autoload that includes all logic, trial and error style? Alter you directory structure to Zend&#8217;s? No! Overload it!</p>
<p>The process is simple, just create your own autoload function and overload it, that way the autoload procedure will run the class through Zend&#8217;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.</p>
<pre><span class="linenum">    1</span> <span class="source source_php"><span class="source source_php source_php_embedded source_php_embedded_block source_php_embedded_block_html"><span class="punctuation punctuation_section punctuation_section_embedded punctuation_section_embedded_begin punctuation_section_embedded_begin_php">&lt;?php</span>
<span class="linenum">    2</span>
<span class="linenum">    3</span> <span class="meta meta_class meta_class_php"><span class="storage storage_type storage_type_class storage_type_class_php">class</span> <span class="entity entity_name entity_name_type entity_name_type_class entity_name_type_class_php">MyLoader</span>{</span>
<span class="linenum">    4</span> <span class="meta meta_function meta_function_php">    <span class="storage storage_modifier storage_modifier_php">public static </span><span class="storage storage_type storage_type_function storage_type_function_php">function</span> <span class="entity entity_name entity_name_function entity_name_function_php">doAutoload</span><span class="punctuation punctuation_definition punctuation_definition_parameters punctuation_definition_parameters_begin punctuation_definition_parameters_begin_php">(</span><span class="meta meta_function meta_function_arguments meta_function_arguments_php"><span class="meta meta_function meta_function_argument meta_function_argument_no-default meta_function_argument_no-default_php"><span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>class</span></span></span>)</span>{
<span class="linenum">    5</span>         <span class="comment comment_line comment_line_double-slash comment_line_double-slash_php"><span class="punctuation punctuation_definition punctuation_definition_comment punctuation_definition_comment_php">//</span>autoload process
</span><span class="linenum">    6</span>         <span class="comment comment_line comment_line_double-slash comment_line_double-slash_php"><span class="punctuation punctuation_definition punctuation_definition_comment punctuation_definition_comment_php">//</span>use file_exists please
</span><span class="linenum">    7</span>     }
<span class="linenum">    8</span> }
<span class="linenum">    9</span>
<span class="linenum">   10</span> <span class="support support_function support_function_php_spl support_function_php_spl_php">spl_autoload_register</span>( <span class="meta meta_array meta_array_php"><span class="support support_function support_function_construct support_function_construct_php">array</span><span class="punctuation punctuation_definition punctuation_definition_array punctuation_definition_array_begin punctuation_definition_array_begin_php">(</span><span class="string string_quoted string_quoted_single string_quoted_single_php"><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_begin punctuation_definition_string_begin_php">'</span><span class="meta meta_string-contents meta_string-contents_quoted meta_string-contents_quoted_single meta_string-contents_quoted_single_php">MyLoader</span><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_end punctuation_definition_string_end_php">'</span></span>, <span class="string string_quoted string_quoted_single string_quoted_single_php"><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_begin punctuation_definition_string_begin_php">'</span><span class="meta meta_string-contents meta_string-contents_quoted meta_string-contents_quoted_single meta_string-contents_quoted_single_php">doAutoload</span><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_end punctuation_definition_string_end_php">'</span></span><span class="punctuation punctuation_definition punctuation_definition_array punctuation_definition_array_end punctuation_definition_array_end_php">)</span></span> )<span class="punctuation punctuation_terminator punctuation_terminator_expression punctuation_terminator_expression_php">;</span>
<span class="linenum">   11</span>
<span class="linenum">   12</span> <span class="punctuation punctuation_section punctuation_section_embedded punctuation_section_embedded_end punctuation_section_embedded_end_php"><span class="source source_php">?</span>&gt;</span></span></span></pre>
<p><strong>Iterators</strong></p>
<p>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&#8217;m not exaggerating at all. This includes iteratorfilters and many others. 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 traversing a directory. In the usual manner you can iterate over scandir, then use <em>if</em> and <em>else</em> to skip over &#8220;.&#8221;,  &#8220;..&#8221; 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:</p>
<pre><span class="linenum">    1</span> <span class="source source_php"><span class="source source_php source_php_embedded source_php_embedded_block source_php_embedded_block_html"><span class="punctuation punctuation_section punctuation_section_embedded punctuation_section_embedded_begin punctuation_section_embedded_begin_php">&lt;?php</span>
<span class="linenum">    2</span>
<span class="linenum">    3</span> <span class="meta meta_class meta_class_php"><span class="storage storage_type storage_type_class storage_type_class_php">class</span> <span class="entity entity_name entity_name_type entity_name_type_class entity_name_type_class_php">RecursiveFileFilterIterator</span> <span class="storage storage_modifier storage_modifier_extends storage_modifier_extends_php">extends</span> <span class="entity entity_other entity_other_inherited-class entity_other_inherited-class_php">FilterIterator</span>
<span class="linenum">    4</span> {</span>
<span class="linenum">    5</span>     <span class="storage storage_modifier storage_modifier_php">protected</span> <span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>ext</span> <span class="keyword keyword_operator keyword_operator_assignment keyword_operator_assignment_php">=</span> <span class="meta meta_array meta_array_php"><span class="support support_function support_function_construct support_function_construct_php">array</span><span class="punctuation punctuation_definition punctuation_definition_array punctuation_definition_array_begin punctuation_definition_array_begin_php">(</span><span class="string string_quoted string_quoted_single string_quoted_single_php"><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_begin punctuation_definition_string_begin_php">'</span><span class="meta meta_string-contents meta_string-contents_quoted meta_string-contents_quoted_single meta_string-contents_quoted_single_php">jpg</span><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_end punctuation_definition_string_end_php">'</span></span>,<span class="string string_quoted string_quoted_single string_quoted_single_php"><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_begin punctuation_definition_string_begin_php">'</span><span class="meta meta_string-contents meta_string-contents_quoted meta_string-contents_quoted_single meta_string-contents_quoted_single_php">gif</span><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_end punctuation_definition_string_end_php">'</span></span><span class="punctuation punctuation_definition punctuation_definition_array punctuation_definition_array_end punctuation_definition_array_end_php">)</span></span><span class="punctuation punctuation_terminator punctuation_terminator_expression punctuation_terminator_expression_php">;</span>
<span class="linenum">    6</span>
<span class="linenum">    7</span>     <span class="comment comment_block comment_block_documentation comment_block_documentation_phpdoc comment_block_documentation_phpdoc_php"><span class="punctuation punctuation_definition punctuation_definition_comment punctuation_definition_comment_php">/**</span>
<span class="linenum">    8</span>     * Takes $path and creates a recursive iterator with a directory iterator
<span class="linenum">    9</span>     * <span class="keyword keyword_other keyword_other_phpdoc keyword_other_phpdoc_php">@param</span> $path diretory to iterate
<span class="linenum">   10</span>     <span class="punctuation punctuation_definition punctuation_definition_comment punctuation_definition_comment_php">*/</span></span>
<span class="linenum">   11</span> <span class="meta meta_function meta_function_php">    <span class="storage storage_modifier storage_modifier_php">public </span><span class="storage storage_type storage_type_function storage_type_function_php">function</span> <span class="support support_function support_function_magic support_function_magic_php">__construct</span><span class="punctuation punctuation_definition punctuation_definition_parameters punctuation_definition_parameters_begin punctuation_definition_parameters_begin_php">(</span><span class="meta meta_function meta_function_arguments meta_function_arguments_php"><span class="meta meta_function meta_function_argument meta_function_argument_no-default meta_function_argument_no-default_php"><span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>path</span></span></span>)</span>
<span class="linenum">   12</span>     {
<span class="linenum">   13</span>         <span class="storage storage_type storage_type_php">parent</span><span class="keyword keyword_operator keyword_operator_class keyword_operator_class_php">::</span><span class="meta meta_function-call meta_function-call_static meta_function-call_static_php">__construct</span>(<span class="keyword keyword_other keyword_other_new keyword_other_new_php">new</span> <span class="support support_class support_class_php">RecursiveIteratorIterator</span>(<span class="keyword keyword_other keyword_other_new keyword_other_new_php">new</span> <span class="support support_class support_class_php">RecursiveDirectoryIterator</span>(<span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>path</span>)))<span class="punctuation punctuation_terminator punctuation_terminator_expression punctuation_terminator_expression_php">;</span>
<span class="linenum">   14</span>     }
<span class="linenum">   15</span>
<span class="linenum">   16</span>     <span class="comment comment_block comment_block_documentation comment_block_documentation_phpdoc comment_block_documentation_phpdoc_php"><span class="punctuation punctuation_definition punctuation_definition_comment punctuation_definition_comment_php">/**</span>
<span class="linenum">   17</span>      * Checks extension names for files only.
<span class="linenum">   18</span>      <span class="punctuation punctuation_definition punctuation_definition_comment punctuation_definition_comment_php">*/</span></span>
<span class="linenum">   19</span> <span class="meta meta_function meta_function_php">    <span class="storage storage_modifier storage_modifier_php">public </span><span class="storage storage_type storage_type_function storage_type_function_php">function</span> <span class="entity entity_name entity_name_function entity_name_function_php">accept</span><span class="punctuation punctuation_definition punctuation_definition_parameters punctuation_definition_parameters_begin punctuation_definition_parameters_begin_php">(</span>)</span>
<span class="linenum">   20</span>     {
<span class="linenum">   21</span>         <span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>item</span> <span class="keyword keyword_operator keyword_operator_assignment keyword_operator_assignment_php">=</span> <span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>this</span><span class="keyword keyword_operator keyword_operator_class keyword_operator_class_php">-&gt;</span><span class="meta meta_function-call meta_function-call_object meta_function-call_object_php">getInnerIterator</span>()<span class="punctuation punctuation_terminator punctuation_terminator_expression punctuation_terminator_expression_php">;</span>
<span class="linenum">   22</span>         <span class="keyword keyword_control keyword_control_php">if</span> (<span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>item</span><span class="keyword keyword_operator keyword_operator_class keyword_operator_class_php">-&gt;</span><span class="meta meta_function-call meta_function-call_object meta_function-call_object_php">isFile</span>() <span class="keyword keyword_operator keyword_operator_logical keyword_operator_logical_php">&amp;&amp;</span> <span class="support support_function support_function_array support_function_array_php">in_array</span>(<span class="support support_function support_function_string support_function_string_php">pathinfo</span>(<span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>item</span><span class="keyword keyword_operator keyword_operator_class keyword_operator_class_php">-&gt;</span><span class="meta meta_function-call meta_function-call_object meta_function-call_object_php">getFilename</span>(), <span class="support support_constant support_constant_std support_constant_std_php">PATHINFO_EXTENSION</span>), <span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>this</span><span class="keyword keyword_operator keyword_operator_class keyword_operator_class_php">-&gt;</span><span class="variable variable_other variable_other_property variable_other_property_php">ext</span>)) {
<span class="linenum">   23</span>             <span class="keyword keyword_control keyword_control_php">return</span> <span class="constant constant_language constant_language_php">TRUE</span><span class="punctuation punctuation_terminator punctuation_terminator_expression punctuation_terminator_expression_php">;</span>
<span class="linenum">   24</span>         }
<span class="linenum">   25</span>     }
<span class="linenum">   26</span> }
<span class="linenum">   27</span>
<span class="linenum">   28</span> <span class="comment comment_line comment_line_double-slash comment_line_double-slash_php"><span class="punctuation punctuation_definition punctuation_definition_comment punctuation_definition_comment_php">//</span> Using it
</span><span class="linenum">   29</span> <span class="keyword keyword_control keyword_control_php">foreach</span> (<span class="keyword keyword_other keyword_other_new keyword_other_new_php">new</span> <span class="support support_class support_class_php">RecursiveFileFilterIterator</span>(<span class="string string_quoted string_quoted_single string_quoted_single_php"><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_begin punctuation_definition_string_begin_php">'</span><span class="meta meta_string-contents meta_string-contents_quoted meta_string-contents_quoted_single meta_string-contents_quoted_single_php">/path/to/something</span><span class="punctuation punctuation_definition punctuation_definition_string punctuation_definition_string_end punctuation_definition_string_end_php">'</span></span>) <span class="keyword keyword_operator keyword_operator_logical keyword_operator_logical_php">as</span> <span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>item</span>) {
<span class="linenum">   30</span>     <span class="support support_function support_function_construct support_function_construct_php">echo</span> <span class="variable variable_other variable_other_php"><span class="punctuation punctuation_definition punctuation_definition_variable punctuation_definition_variable_php">$</span>item</span> <span class="keyword keyword_operator keyword_operator_string keyword_operator_string_php">.</span> <span class="support support_constant support_constant_core support_constant_core_php">PHP_EOL</span><span class="punctuation punctuation_terminator punctuation_terminator_expression punctuation_terminator_expression_php">;</span>
<span class="linenum">   31</span> }
<span class="linenum">   32</span>
<span class="linenum">   33</span> <span class="punctuation punctuation_section punctuation_section_embedded punctuation_section_embedded_end punctuation_section_embedded_end_php"><span class="source source_php">?</span>&gt;</span></span></span></pre>
<p>You may argue that now you have much more code, I&#8217;ll reply: yes, but you have reusable and testable code!</p>
<p>Here are some more iterators:</p>
<ul>
<li>RecursiveIterator</li>
<li>RecursiveIteratorIterator</li>
<li>OuterIterator</li>
<li>IteratorIterator</li>
<li>FilterIterator</li>
<li>RecursiveFilterIterator</li>
<li>ParentIterator</li>
<li>SeekableIterator</li>
<li>LimitIterator</li>
<li>GlobIterator</li>
<li>CachingIterator</li>
<li>RecursiveCachingIterator</li>
<li>NoRewindIterator</li>
<li>AppendIterator</li>
<li>RecursiveIteratorIterator</li>
<li>InfiniteIterator</li>
<li>RegexIterator</li>
<li>RecursiveRegexIterator</li>
<li>EmptyIterator</li>
<li>RecursiveTreeIterator</li>
<li>ArrayIterator</li>
</ul>
<p>As of PHP 5.3 we have some other interesting tools, like SPLInt and other types you can use for type-casting. One class worth mencioning however is:</p>
<p><strong>SplFixedArray</strong></p>
<p>Why? Its faster! Why? aha! that&#8217;s the million dollar question. See to understand that we must delve into the PHP internals for a regular array. In a regular array you can use different 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 caught up, yes, it is a C array! Which explains why this is faster than regular arrays. (only php5.3!!)</p>
<p>These are just some examples of what you can do with SPL, unfortunately there is no single place to go and get a complete view of SPL. You can hit the <a href="http://php.net/spl">regular manual</a>, but you should always trust in this <a href="http://www.php.net/~helly/php/ext/spl/">documentation</a>, done by the creators themselves, or you can hit <a href="http://elizabethmariesmith.com/">Elizabeth&#8217;s Blog</a>, most examples on this article belong to her.</p>
<p><strong>Invitation</strong></p>
<p>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 <a href="http://doc.php.net">php.doc mailing list</a>, or IRC your way to EFNet and join #php.doc and say &#8220;I want to help&#8221;, you will be given a task very fast!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mihswat.com/2009/06/08/spl-the-hidden-gem/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

