phpcontent-for

How could you create a "content_for" equivalent in PHP?


I've been working on a small page in PHP, one that doesn't need the power of a full-fledged framework behind it. One thing that I'm really missing from previous work in Ruby-on-Rails is the ability to effectively pass content up the page using "content_for".

What I was wondering is, how could you create a page lifecycle that would accomplish this same effect in PHP?

So, here's a simple example:

Let's say you have a template that defines an index page, just a recurring header and menu you want to use on all your pages. So your index.php file looks basically like this:

...header stuff...
<body>
<?php include $file.'.php'; ?>
</body>
...footer stuff...

EDIT: Thanks for the tips on URL security, but let's just assume I'm getting the user request safely :)

Now, lets say in the header you want to put this:

<head>
<title><?php echo $page_title; ?></title>
</head>

It would be nice to be able to specify the title in the included file, so at the url http://example.com/index.php?p=test you're loading test.php, and that file looks like this:

<?php $page_title = 'Test Page'; ?>
... rest of content ...

Now, obviously this doesn't work, because the including page (index.php) is loaded before the variable is set.

In Rails this is where you could pass stuff 'up the page' using the content_for function.

My question is this: What would be the simplest, leanest way that you all can think of to effect this kind of 'content_for' functionality in PHP?

Ideally I'd like suggestions that don't involve strapping on some big framework, but some relatively light boilerplate code that could be used in a lot of different applications.


Solution

    1. Never do include $_GET['p']. This opens a huge security hole in your site, as include accepts filenames and URLs, so anybody would be able to read any file on your site and also execute any code on your server. You may want to check and sanitize the value first.

    2. If you need something simple, you may put header and footer in separate files, execute your test.php which would set the variables, capture its output using output buffering, then include the header, output the middle part and include the footer. Example:

       <?php ob_start(); ?>
       <body>
       <?php include $filename.'.php'; ?>
       </body>
       <?php $content = ob_get_clean(); 
        include 'header.php';
        echo $content;
        include 'footer.php';
        ?>