Skip to content

Instantly share code, notes, and snippets.

@code-poel
Last active December 20, 2015 12:29
Show Gist options
  • Save code-poel/6130996 to your computer and use it in GitHub Desktop.
Save code-poel/6130996 to your computer and use it in GitHub Desktop.
Nested SPL objects with recursion.
<?php
class Layout extends \ArrayIterator
{
}
class Block extends \ArrayIterator
{
protected $_alias;
public function __construct( $alias = null )
{
if( is_null( $alias ) )
{
$alias = uniqid( 'Block_' );
}
$this->_alias = $alias;
}
public function getAlias()
{
return $this->_alias;
}
}
try
{
$b1 = new Block( 'Base' );
$b1_b1 = new Block( 'Base > 1st Child' );
$b1_b2 = new Block( 'Base > 2nd Child' );
$b1_b1_b1 = new Block( 'Base > 1st Child > 1st Child' );
$b1_b1->append( $b1_b1_b1 );
$b1->append( $b1_b1 );
$b1->append( $b1_b2 );
$layout = new Layout;
$layout->append( $b1 );
$storage = new \RecursiveIteratorIterator( new \RecursiveArrayIterator( $layout ), RecursiveIteratorIterator::SELF_FIRST );
foreach( $storage as $key => $value )
{
print_r( $value->getAlias() . PHP_EOL );
}
}
catch( \Exception $e )
{
var_dump( $e->getMessage() );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment