Looping class, for template engine kind of thing

Posted by tarnfeld on Stack Overflow See other posts from Stack Overflow or by tarnfeld
Published on 2010-05-07T20:55:38Z Indexed on 2010/05/07 20:58 UTC
Read the original article Hit count: 173

Filed under:
|
|

Hey, I am updating my class Nesty so it's infinite but I'm having a little trouble.... Here is the class:

<?php

Class Nesty
{

    // Class Variables
    private $text;
    private $data = array();
    private $loops = 0;
    private $maxLoops = 0;

    public function __construct($text,$data = array(),$maxLoops = 5)
    {
        // Set the class vars
        $this->text = $text;
        $this->data = $data;
        $this->maxLoops = $maxLoops;

    }

    // Loop funtion
    private function loopThrough($data)
    {

        if( ($this->loops +1) > $this->maxLoops )
        {
            die("ERROR: Too many loops!");
        }
        else
        {
            $keys = array_keys($data);

            for($x = 0; $x < count($keys); $x++)
            {
                if(is_array($data[$keys[$x]]))
                {
                    $this->loopThrough($data[$keys[$x]]);
                }
                else
                {
                    return $data[$keys[$x]];
                }
            }
        }

    }

    // Templater method
    public function template()
    {
        echo $this->loopThrough($this->data);
    }

}

?>

Here is the code you would use to create an instance of the class:

<?php

// The nested array
$data = array(
    "person" => array(
        "name" => "Tom Arnfeld",
        "age" => 15
    ),
    "product" => array (
        "name" => "Cakes",
        "price" => array (
            "single" => 59,
            "double" => 99
        )
    ),
    "other" => "string"
);  

// Retreive the template text
$file = "TestData.tpl";
$fp = fopen($file,"r");
$text = fread($fp,filesize($file));

// Create the Nesty object
require_once('Nesty.php');
$nesty = new Nesty($text,$data);

// Save the newly templated text to a variable $message
$message = $nesty->template();

// Print out $message on the page
echo("<pre>".$message."</pre>");

?>

Any ideas?

© Stack Overflow or respective owner

Related posts about class

Related posts about array