[TYPO3-ect] PHP5 and SPL

Elmar Hinz elmar.DOT.hinz at team.MINUS.red.DOT.net
Mon Mar 20 07:58:19 CET 2006


Hello typoniks,

How do we prepare for PHP5 features while it still runs on PHP4 for a
year or two?

I studied the new features of PHP5 and I am very lucky with it. It
will solve a lot of my daily proplems like simply parsing and
accessing XML[1] or really comfortable handling of objects in the
array like way. [2]

One of the most impressing and usefull parts that found their way into
PHP5 is SPL. So that we can base our work on it. SPL is the akronym
for Standard PHP Library and currently deals with arrays, objects and
iterators. [3]

What does SPL do? To abstract it: It defines and implements two or
three important interfaces:

Iterator: [4]

 	current ()
 	key ()
 	next ()
 	rewind ()
 	valid ()

ArrayAccess: [5][8]

 	offsetExists ($offset)
 	offsetGet ($offset)
 	offsetSet ($offset, $value)
 	offsetUnset ($offset)
        ( append($value) )

If your object implements Iterator you can iterate it in foreach in
PHP5, just like a usual array.

foreach($myObject as $key => $value){
	do something ...
}

If your object implements ArrayAccess you can use it like an array in
PHP5.

$myObject[] = 'firstElement';
$myObject[] = 'secondElement';

I guess you directly see the 2 mayor uses of it:

1.) Definition of a standared way to iterate lists.
2.) Very simple iterating of objects with the standard tools for arrays.

You can provide iterators for whatever you want: directories, file
content, xml(recursive use), resultsets, ... and you can work with
them all this different stuff by the same tools. [6][7]


Do we have to wait for PHP5 to gain this advantages?

The answer is NO. We can do already:

- implement this functions
- prepare our objects for PHP5
- make advantage of the iterator pattern
- reuse our objects in different places

We still can't do this in PHP4:

$myObject[$key] = 'element';
$myObject[] = 'element';

but replace it with:

$myObject->offsetSet($key, 'element');
$myObject->append('element');


We still can't use the foreach loop in PHP4 but we can replace it with
the while loop:

while($myObject->valid()){
  $key = $myObject->key();
  $value = $myObject->value();

  do something ... with $key, $value

  $myObject->next();
}

I propose to add this interfaces to the TYPO3 coding guidelines. At
least we should start to work on this basis inside ECT.

Regards

Elmar


[1] http://de2.php.net/simplexml
[2] http://de2.php.net/manual/en/language.oop5.iterations.php
[3]http://de2.php.net/manual/en/ref.spl.php
[4] http://www.php.net/~helly/php/ext/spl/interfaceIterator.html
[5] http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html
[6] http://www.phpro.org/tutorials/Introduction-to-SPL.html
[7] http://www.sitepoint.com/print/php5-standard-library
[8] http://www.php.net/~helly/php/ext/spl/classArrayIterator.html




























More information about the TYPO3-team-extension-coordination mailing list