Home arrow PHP arrow Page 2 - PHP Closures as View Helpers: Lazy-Loading File Data

A Final Example - PHP

In this second part of a two-part tutorial, you'll learn how to use closures in the development of an extendable template system. This system can be customized at will without struggling too much, thanks to the number of interfaces that it implements.

  1. PHP Closures as View Helpers: Lazy-Loading File Data
  2. A Final Example
By: Alejandro Gervasio
Rating: starstarstarstarstar / 0
January 30, 2012

print this article



To demonstrate how easy it is to pull in file data on request by using the pair of classes defined in the previous section, it’s necessary to create the pertinent file and populate it with some trivial content. To make things shorter and easier to follow, I’ll be working with a file called “data.txt,” which is the default one used by the earlier “FileHandler” class.

The sample file looks like this:


s:83:"This content has been lazy-loaded from a remote resource via an anonymous function.";

As you can see, the target file now contains a simplistic serialized string (but it could be anything else, like an array, an object and so forth), which definitely doesn’t bear any further explanation. That was the boring part, so it’s time to show how to use the power of closures to lazy-load this string and drop it into the same template file used in the previous tutorial.

In case you don’t recall how this template looked, here it is:


<!doctype html>
<meta charset="utf-8">
<title>Using closures in PHP</title>
        <h1>Header section</h1>
        <h2>Welcome! You're accessing this page from : <?php echo $this->clientIp;?></h2>
        <p><?php echo $this->header;?></p>
        <h2>Main section</h2>
        <p><?php echo $this->content;?></p>
        <h2>Footer section</h2>
        <p><?php echo $this->footer;?></p>

Here is where things become really interesting, trust me. See the view field “$this->content” interspersed in the template’s main section? Well, in a typical use case, it should FIRST be populated with a dynamically-generated value (i.e. some database records) and then echoed to the screen. Thanks to the functionality of closures, though, it’s possible to delay this process until the template is actually rendered. If this sounds rather messy to you, make sure to peek at the following code snippet. It uses the previous “Serializer” and “FileHandler” classes to accomplish this. 


use MyApplication\View,

// include the autoloader and create an instance of it
require_once __DIR__ . '/Autoloader.php';
$autoloader = new Autoloader;

// create a view object
$view = new View;
$view->header = 'This is the content of the header section';
$view->footer = 'This is the content of the footer section';
$view->clientIp = $_SERVER['REMOTE_ADDR'];

// lazy load contents from a remote file and assign them to the 'content' field
$view->content = function() {
    $fileHandler = new FileHandler(new Serializer);
    return $fileHandler->read();

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

There you have it. As shown above, once a view object is created, the aforementioned classes are wrapped inside a closure, which is then assigned to the corresponding  “content” property. Finally, the view is dumped to the browser. This process generates the following output:

There you have it. Not only was the whole template rendered as expected, but the string placed in the “data.txt” file was retrieved on request and printed on screen.

Even though somewhat contrived, this example shows how to take advantage of anonymous functions for lazy-loading data from a persistence layer (in this case, a simple text file). So, go ahead and start discovering new and creative ways to spice up your OO applications with the functionality of closures. It’ll be a fun experience.  

Closing Remarks

We've come to the end of this tutorial. But hopefully the journey has been instructive, as you learned how to use closures in the development of an extendable template system, which can be customized at will thanks to the number of interfaces that it implements.

As you just saw, a proper mixture of anonymous functions, along with a few basic classes, is all you need to set up a flexible structure -- a structure which allows you to parse template variables and execute different processes on request with remarkable ease.

To make a long story short: if you haven’t used closures before in your OO applications, or simply are looking new ways to get the most out of them, the code samples in this article should point you in the right direction.

See you in the next PHP development tutorial!          

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- 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: