Created
March 21, 2012 09:35
-
-
Save RalfAlbert/2145820 to your computer and use it in GitHub Desktop.
Example 3 for Formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'class-formatter.php'; | |
require_once 'class-templates.php'; | |
interface Templates | |
{ | |
public function get_templates(); | |
} | |
class Lister extends Formatter | |
{ | |
public $templates_object = NULL; | |
public $templates = array(); | |
public function __construct( Templates $templates ){ | |
$this->templates_object = &$templates; | |
$this->get_templates(); | |
} | |
protected function get_templates(){ | |
if( NULL === $this->templates_object ) | |
throw new Exception( 'No templates defined' ); | |
$this->templates = &$this->templates_object->get_templates(); | |
} | |
public function get_list( $type = '', $data = array() ){ | |
// get templates if not already set | |
if( empty( $this->templates ) ) | |
$this->get_templates(); | |
// check if the requested list-typ is defined | |
if( ! in_array( $type, array_keys( $this->templates ) ) ) | |
return FALSE; | |
// create list | |
$inner = new stdClass(); | |
$values = new stdClass(); | |
foreach( $data as $key => $value ){ | |
$values->key = $key; | |
$values->item = $value; | |
$inner->inner .= self::sprintf( $this->templates[$type]['inner'], $values ); | |
} | |
return self::sprintf( $this->templates[$type]['outer'], $inner ); | |
} | |
} | |
$data = array( 'Eins', 'Zwei', 'Drei' ); | |
$list = new Lister( new Simple_List_Templates ); | |
echo $list->get_list( 'ol', $data ); | |
echo $list->get_list( 'ul', $data ); | |
echo $list->get_list( 'div', $data ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Simple_List_Templates implements Templates | |
{ | |
public function get_templates(){ | |
return array( | |
'ol' => array( | |
'outer' => "<ol>\n%inner%</ol>\n", | |
'inner' => "<li>%item%</li>\n" | |
), | |
'ul' => array( | |
'outer' => "<ul>\n%inner%</ul>\n", | |
'inner' => "<li>%item%</li>\n" | |
), | |
'div' => array( | |
'outer' => "<div>\n%inner%</div>\n", | |
'inner' => "<p>%item%</p>\n" | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment