Home arrow PHP arrow Page 2 - ArrayObject PHP Class Examples

Building a View Class with PHP ArrayObject - PHP

In this second part of a two-part series on the ArrayObject class from the Standard PHP Library, you'll learn how to handle properties by means of an object syntax.

TABLE OF CONTENTS:
  1. ArrayObject PHP Class Examples
  2. Building a View Class with PHP ArrayObject
By: Alejandro Gervasio
Rating: starstarstarstarstar / 0
November 16, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

To be frank, there are many situations where itís possible to use the ArrayObject class as a base implementation and get pretty satisfactory results. However, one case where this is especially useful occurs when you need to create a view class that gets assigned a set of properties dynamically, which are later populated within an associated template file.

If you're wondering how such a view class looks, just check out the example below:

<?php

namespace ArrayObject;

class View extends \ArrayObject
{
    const DEFAULT_TEMPLATE_FILE = 'default_template.php';
    protected $_templateFile;
   
    /**
     * Constructor
     */
    public function __construct(array $fields = array(), $templateFile = self::DEFAULT_TEMPLATE_FILE)
    {
        parent::__construct($fields, \ArrayObject::ARRAY_AS_PROPS);
        $this->setTemplateFile($templateFile);
    }
   
    /**
     * Set the template file
     */
    public function setTemplateFile($templateFile)
    {
        if (!file_exists($templateFile) || !is_readable($templateFile)) {
            throw new \InvalidArgumentException('The specified template file is invalid.');
        }
        $this->_templateFile = $templateFile;
    }
   
    /**
     * Get the template file
     */
    public function getTemplateFile()
    {
       return $this->_templateFile;
    }
   
    /**
     * Reset the template file to the default one
     */
    public function resetTemplateFile()
    {
        $this->_templateFile = self::DEFAULT_TEMPLATE_FILE;
    }
     
    /**
     * Render the template file
     */
    public function render()
    {
        $fields = $this->getArrayCopy();
        extract($fields);
        include $this->_templateFile;
        return ob_get_clean();
    }    
}

From the previous code snippet, itís easy to see the inner workings of the View class. Aside from extending ArrayObject, the class implements a few additional methods. These allow it to render the associated template file, set a new one and even reset it to a default value. 

With this sample view class already up and running, the next step is to put it into action. Say a default template looks like this: 

(default_template.php)

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Using the ArrayObject PHP class</title>
</head>
<body>
    <header>
        <h1><?php echo $header;?></h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </header>
    <section>
        <h2><?php echo $content;?></h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </section>
    <footer>
        <h2><?php echo $footer;?></h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </footer>
</body>
</html>

In this case, creating a populated view object and rendering the template could be achieved in the following way:

<?php

namespace ArrayObject;

require_once 'View.php';

// create an instance of the View class and assign some properties to it
$view = new View(array(
    'header'  => 'This is the header section',
    'content' => 'This the content section',
    'footer'  => 'This is the footer section'
));

// render the view (uses the default template file)
echo $view->render();

That was really easy to code and read, wasnít it? Furthermore, since the flexibility of ArrayObject is actually the backbone of the View class, the earlier script could be rewritten as follows:

<?php

namespace ArrayObject;

require_once 'View.php';

// create an instance of the View class
$view = new View;

// assign some properties to the view object
$view->header = 'This is the header section';
$view->content = 'This the content section';
$view->footer  = 'This is the footer section';

// render the view (uses the default template file)
echo $view->render();

There you have it. Regardless of the script that best suits your personal taste (it might even be both), the template file will be rendered on screen, and the embedded variables will be properly populated as expected.

Of course, itís possible to further extend the view class, so that it can perform a few more complex tasks. In any case, you can see pretty clearly how to reuse the functionality of ArrayObject in a real world situation. So, go ahead and give the class a try. 

Closing Remarks

In this two-part tutorial, I provided you with a quick introduction to the main features offered by the ArrayObject SPL class, and also showed you how to tweak its behavior by using its STD_PROP_LIST  and ARRAY_AS_PROPS constants. Naturally, this lesson would have been somewhat useless without setting up an example that demonstrated how to employ the class in a more realistic situation.

To address this issue, I went through the development of a simple view class, which not only extended the core functionality of ArrayObject, but could render a template file and populate the set of properties embedded within it. While this example was pretty basic, it showed how easy it is to exploit the abilities offered by ArrayObject to spawn a refined implementation of it.

So, now that you have a clear idea of what this rather overlooked SPL class can do for you, feel free to utilize it when developing your own PHP applications. If you can happily live with its biggest limitation (that it canít be used with most of the native PHP array functions) it might be worth looking into. 

See you in the next PHP tutorial!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: