ArrayObject PHP Class Examples

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.

As one of the building blocks of the Standard PHP Library (SPL), the ArrayObject class is a traversable, countable structure, which allows you to treat objects as arrays. This functionality seems  irrelevant at first sight, but the class may be a real time-saver in certain situations. That’s especially true when you need to create custom implementations (for instance, a dynamic registry or a service locator) without having to implement from scratch the ArrayAccess, IteratorAggregate and Countable SPL interfaces.

The best way to get things rolling with ArrayObject is by example. In the first part of this tutorial I created several examples that demonstrated how to assign, count and traverse the properties assigned to some instances of this class by using an array notation. Even though the examples were pretty contrived, they illustrated how versatile the class can be in a decent variety of situations.

It’s valid to point out, though, that ArrayObject’s abilities aren’t limited to handling properties as if they were array elements. When the constant (or flag, in the class’s jargon) ARRAY_AS_PROPS is passed to the constructor or to the “setFlags()” method, it’s possible to handle the properties by means of an object syntax.

Given that, in this last part of the tutorial I’ll be showing you how to accomplish this. Not only that, but if you wish to see how to use ArrayObject in a more realistic case, I’ll be constructing an extendable view class, which will use ArrayObject’s functionality as the base implementation.       

Now let’s get started.

Using the ArrayObject Class: Assigning Properties by Using an Object Notation

As I just explained, it’s really simple to instruct the ArrayObject class to handle its properties in an object-based manner, instead of as array elements. Getting this behavior is as easy as passing the constant ARRAY_AS_PROPS to the class’s constructor.

As usual, the most instructive way to grasp the logic of this process is by examining a concrete code sample. Therefore, be sure to take a peek at the one below, which hopefully will be quite illustrative:

<?php

namespace ArrayObject;

$data = array(
    ‘name’  => ‘John Doe’,
    ‘email’ => ‘john@domain.com’
);

// create an instance of the ArrayObject class
$arrayObj = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);

// access the object properties using an object notation
echo ‘Full name: ‘ . $arrayObj->name . ‘ Email: ‘ . $arrayObj->email;
// displays the following: Full name: John Doe Email: john@domain.com

// count the number of properties in the object
echo ‘Number of properties assigned to the object: ‘ . count($arrayObj);
// displays the following: Number of properties assigned to the object: 2

// dump the array object
var_dump($arrayObj);
/* displays the following

object(ArrayObject)#1 (1) { ["storage":"ArrayObject":private]=> array(2) { ["name"]=> string(8) "John Doe" ["email"]=> string(15) "john@domain.com" } }

*/
// put the array object in a foreach loop
foreach ($arrayObj as $key => $value) {
    echo ‘Key: ‘ . $key . ‘ Value: ‘ . $value . ‘<br />';
}
/* displays the following

Key: name Value: John Doe
Key: email Value: john@domain.com

*/

Definitely, you shouldn’t have any trouble understanding how the script above does its business. It’s pretty similar to those you saw in the previous article. In this case, though, things are slightly different; the aforementioned ARRAY_AS_PROPS flag has been passed to the ArrayObject class upon construction. This minor modification allows it to access the properties assigned to it by using an object notation.

Please be aware that the behavior of the class when using the ARRAY_AS_PROPS flag might be a little quirky, depending on the PHP version that you’re using. So, if you notice this issue, make sure to update your PHP installation to the latest release.

Having clarified that point, now that you’ve learned how to massage the ArrayObject class to behave like a “true” object, it’s time to show off the class’s functionality in a more realistic use case. In the next section I’ll be building a simple view class which will be an extension of ArrayObject.

{mospagebreak title=Building a View Class with PHP ArrayObject}

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!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan