Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Understanding Design Patterns - Iterator
May 30, 2018 @ 10:25:33

The StarTutorial.com site has posted the next in its series covering the definition and use of design patterns in PHP applications. In this latest tutorial they cover the Iterator pattern.

[The Iterator pattern] provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Much like the previous parts of the series, they set up a sample situation to show how the code could be created and how it can be refactored to use the design pattern. In this case, it's an example of women's versus men's products and the fact that they store their inventory differently behind the scenes. The initial code tries to manually merge these two lists by getting the names from each. This is then refactored to define the product types as iterators and pulling the information using a unified interface.

tagged: designpattern iterator introduction tutorial

Link: https://www.startutorial.com/articles/view/understanding-design-patterns-iterator

Michelangelo van Dam:
Speeding up database calls with PDO and iterators
Jul 27, 2015 @ 08:45:28

In a post to his site Michelangelo van Dam shows you how to speed up database calls with PDO and iterators in a "no framework" environment.

When you review lots of code, you often wonder why things were written the way they were. Especially when making expensive calls to a database, I still see things that could and should be improved.

When working with a framework, mostly these database calls are optimized for the developer and abstract the complex logic to improve and optimize the retrieval and usage of data. But then developers need to build something without a framework and end up using the basics of PHP in a sub-optimal way.

He points out some of the common issues with a simple approach using just PDO and simple arrays including performance issues. Instead he recommends the use of iterators that wrap a PDO connection and allow for much simpler fetching and iteration of the found results. He includes code examples for a base iterator instance and a way to extend it to get the customized results. He also includes a few benchmarks showing the difference between a foreach loop and this iterator method.

tagged: database pdo iterator foreach benchmark compare

Link: http://www.dragonbe.com/2015/07/speeding-up-database-calls-with-pdo-and.html

Edd Mann:
Implementing Streams in PHP
Jan 16, 2015 @ 10:09:22

Edd Mann has a new post today looking at implementing streams in your PHP applications. In this case we're not talking about the streams built into PHP but the concept of a source of information that only produces the next item when requested (aka "lazy loading").

Typically, when we think about a list of elements we assume there is both a start and finite end. In this example the list has been precomputed and stored for subsequent traversal and transformation. If instead, we replaced the finite ending with a promise to return the next element in the sequence, we would have the architecture to provide infinite lists. Not only would these lists be capable of generating infinite elements, but they would also be lazy, only producing the next element in the sequence when absolutely required. This concept is called a Stream, commonly also referred to as a lazy list, and is a foundational concept in languages such as Haskell.

He talks about how streams of data should be interacted with differently than a finite list of data and the promises they're based on to provide the right data. He shows two different approaches to implementing a an object to stream data from - a class-based method and one that uses generators. Sample code is provided for each with the generator approach being a bit shorter as they're designed to lazy load items as requested.

tagged: stream data lazyload generator class iterator tutorial

Link: http://eddmann.com/posts/implementing-streams-in-php/

Derick Rethans:
Parallelizing document retrieval
Dec 09, 2014 @ 11:59:20

In his latest post Derick Rethans shows how to parallelize document retrieval from a MongoDB database via PHP. This makes it possible to speed up the read operation caused by reading each item one at a time.

MongoDB 2.6 has a new feature that allows you to read all the documents from one collection with multiple cursors in parallel. This is done through a database command called parallelCollectionScan. The idea behind it is that it is faster then reading all the documents in a collection sequentially.

He includes an example snippet that enables the "parallelCollectionScan" handling for a "cities" collection and the resulting output. He shows how to manually create MongoCommandCursors (or let the driver do it for you) and use PHP's own MultipleIterator to process all of the cursors at essentially the same time.

tagged: mongodb driver parallel document retrieval cursor iterator

Link: http://derickrethans.nl/parallelcollectionscan.html

SitePoint PHP Blog:
Fun with Array Interfaces
Dec 09, 2013 @ 10:53:06

On the SitePoint PHP Blog a tutorial has been posted recently about having some fun with array interfaces via some of the functionality provided through the SPL (Standard PHP Library).

As a programmer who works with different languages every day, I find a lot of joy in learning how things are done differently in other languages and seeing if I can do the same in PHP. One thing I liked in particular in Python was how one can emulate features of native data types in custom classes. [...] I thought it would be nice if you could do the same in PHP on an instance of your custom classes and not only arrays. PHP lets us do this with array interfaces.

He illustrates his intent with some basic Python functionality and shows how to use various PHP interfaces to achieve a similar functionality. He talks about SPL interfaces like Countable, ArrayAccess and Iterator to make objects more useful in an array handling environment. His example uses the idea of a set of user's tweets (from Twitter) and shows the implementation of these three interfaces.

tagged: array interface countable arrayaccess iterator tutorial

Link: http://www.sitepoint.com/fun-array-interfaces

Bob Majdak:
Extending an Iterator to use an Iterator to make your code a little cleaner
Mar 12, 2013 @ 09:25:04

In this new post to his site Bob Majdak talks about extending iterators to help make it easier to customize it for your needs.

One of the nice things about iterators is the ability to shove them into other iterators, allowing you to wrap their functionality in other functionality to return a more precise result set. Take for example the idea that we want to read a directory to list only the images inside of it. There are two main ways to do this, via readdir functions and via FilesystemIterator objects. Going the FilesystemIterator route, one common way seems to be extend another class called FilterIterator which allows you to customize a filter based on you overwriting a method called accept().

He shows not only overriding the "accept" method, but also the constructor to make using this new iterator a much simpler (and cleaner) call. You can find out more about the FilesystemIterator (and others) over in the Iterators section of the PHP manual.

tagged: extend iterator clean code accept constructor filesystemiterator


Painless Data Traversal with PHP FilterIterators
Oct 25, 2012 @ 08:54:35

On the MaltBlue blog Matt Setter has a new post introducing you to using FilterIterators for data traversal:

There’s load of ways to traverse data, especially in PHP where there are a variety of loops available; including while, do while, for and foreach. These are fine for normal structures, such as scalar and associative arrays. But what if you want to get a bit more fancy?

He includes a bit of code showing the typical looping approach that a lot of developers take and how, using a FilterIterator, you can extend the default and make a custom "accept" method to remove certain matching items from the data set.

tagged: filteriterator data traversal filter spl iterator array


List Files and Directories with PHP
Oct 23, 2012 @ 08:56:25

On PHPMaster.com there's a new tutorial showing you how to work with files and directories through your PHP applications.

In this article I’ll talk about a common task you might have experienced while developing a PHP application: listing files and directories. I’ll discuss several basic and advanced solutions, each having its pros and cons. First I’ll present three approaches that use some very basic PHP functions and then progress to more robust ones which make use of SPL Iterators.

The solutions they look at are the built-in functions like glob and readdir/opendir as well as SPL iterators up for the task - FilesystemIterator, RecursiveDirectoryIterator and GlobIterator. Code samples are included in the post, showing how to use each method to get and list the files. A few helpful hints are also included to finish off the tutorial (mostly about "tricks" to using the functions effectively).

tagged: tutorial file directory list spl iterator


Web Mozarts:
Give the Traversable Interface Some Love
Oct 10, 2012 @ 09:12:56

In this recent post to the Web Mozarts site, Bernhard Schussek "gives Traversable some love" and introduces you to the Traversable interface and how it might work better for certain things than an Iterator.

Let’s start with a simple use case. Let’s create an interface ArrayInterface that demarcates objects that behave like PHP arrays. The interface should allow for counting, iterating and array access.

He shows how to create this interface based off of a "ArrayInterface" that implements "Countable", "ArrayAccess" and "Iterator" with all of the methods required for each. He points out that, while the documentation in the manual makes "Traversable" shouldn't be used, it can be extended instead of Iterator. This gives other classes that extend this interface the option of extending either of the Iterators ("Iterator" or "IteratorAggregate") they want.

tagged: interface traversable introduction iterator iteratoraggregate


Thomas Weinart:
What Iterators Can Do For You
Aug 01, 2012 @ 09:55:22

Thomas Weinert has a new post to his site showing some of the things that iterators can do for you (including working with arrays and aggregation).

Basically Iterators provide a list interface for an object. Like all interfaces they are a contract how something can be used. If you use an interface it is not relevant how it is implemented - the implementation logic is encapsulated. It is of course relevant on the integration level. A bad implementation can impact the performance of you application. Even an good implementation may need special resources (like a database). But all this does not impact how you use it. Your code using the object with the Iterator interface stays the same.

He shows how to use the IteratorAggregate, ArrayIterator, FilterIterator and how to create a custom Iterator that you can extend in your own code.

tagged: iterator tutorial array filter aggregate custom