PTE - Page 3

Another method I've used while doing PTE is used when looping.

If your code is object oriented, and you're including your template from inside an object, I have found the following to be a good pattern to follow. The idea is to not require the template author know about PHP object oriented programming - to avoid the use of $this->. The template code is simple and clean, however, I would love to find a way to put the extract into the for construct to make it even cleaner but after some experimenting I don't think this is possible.

for ( $this->startRecords(); $row = $this->getRowVars(); $this->nextRecord() )
{
    extract( $row );
	?>
    Template Here
    <?
}

The relevant functions from the object look like this

function startRecords()
{
    $this->currentRecord = 0;
    $this->recordCount = count( $this->records );
}

function getRowVars()
{
    $result = false;

    if ( $this->currentRecord < $this->recordCount )
    {
        $result = $this->records[$this->currentRecord];
    }

    return $result;
}


function nextRecord()
{
    $this->currentRecord++;
}

At first glance, it might seem silly to use the functions to accomplish what could be accomplished without them, but there is a lot that can be done to allow descendant objects to add to or override values in the records array. One would do this in the getRowVars method. Another purpose of this would be to actually use a database call to retrieve the next record from the database thereby reducing the memory requirements of your script.

Let me point something out. Except for loops (our object-oriented for-loops are generic enough to make it possible to simply do a copy-paste) all php code in templates is procedural - this way the template writer does not need to know about our objects, and they don't have to worry about changing their templates if we change our object - all we developers have to do is make sure we're getting valid data into the local variable scope of the function that is including our template.


Which brings me to my next point. If you don't want to worry about using objects, or don't need to have your object keep track of records, you can simply loop through an array like you normally would in PHP.

Assuming you have this data

$items[0]['Title'] = 'ThePhpPro';
$items[0]['URL']   = 'http://www.thephppro.com/';

include( 'template.php' );

You could use this template:

// template.php
for ( $ix = 0; $ix < count( $items ); $ix++ )
{
	extract( $items[$ix] );
    ?>
        <a href="<?= $URL; ?>"><?= $Title; ?><?</a>< /br>
    <?
}

Continue Reading on Page 4

Jump to page: _1_ | _2_ | _3_ | _4_ | _5_ | _6_

Thank you for reading! Feedback may be left by using the contact form
Interesting and/or informative comments will be posted on the article comment page.


For web site hosting I recommend - www.bluehost.com