A simple content_for in PHP
Posted June 3rd, 2010; 2 comments.
I’d been meaning to check out PHP 5.3’s closures. When someone asked me a question about Fitzgerald today, I had to look at the source to find the answer. I then spent five minutes sketching the following, which is a very minimal implementation of Rails’ content_for view helper.
<?php $contents = array(); function content_for($name, $method) { global $contents; $contents[$name] = $method; } function yield($name) { global $contents; if (array_key_exists($name, $contents)) { return $contents[$name](); } } $variable = "something great"; ?> <?php content_for('header', function() use($variable) { ?> <h1>'<?php echo $variable ?>' should be in the header</h1> <?php })?> <?php content_for('footer', function() { ?> <h1>should be in the footer</h1> <?php })?> <div class="header"> <?php yield('header')?> </div> <p>Here is the content for a page.</p> <div class="footer"> <?php yield('footer')?> </div>
The rendered result looks like this:
<div class="header"> <h1>'something great' should be in the header</h1> </div> <p>Here is the content for a page.</p> <div class="footer"> <h1>should be in the footer</h1> </div>
Having to declare inherited variables with use is a little annoying, but otherwise, I’m impressed with this addition to PHP.