Page 1 of 1

Basic PHP Design Questions

Posted: Wed May 13, 2009 9:18 pm
by gdtyra
I've mainly used Ruby on Rails in the past, but I'm moving to PHP for performance reasons.

My first question is about design templates. So far I've seen two ways to do it, making PHP files for the header, menu, footer, etc. and using include, or using Smarty. Are there any other common ways I should know about?

My second question is about the use of echo. Let's say I want to loop through a set of data and render some divs for each one. In RoR, it could be done like this:

Code: Select all

 
<% @data.each do |d| %>
    <div id="some_div">
    <p>blah blah</p>
    </div>
<% end %>
 
But in PHP, the only way i know to do it would be like this:

Code: Select all

 
foreach ($data as $d)
{
   echo "<div id ='some_div'>";
   echo "<p>blah blah</p>";
   echo "</div>";
}
 
Since it's within PHP code, do I always need to use echo to render HTML? Or is there a cleaner way, such as the RoR way?

Thanks!

Re: Basic PHP Design Questions

Posted: Wed May 13, 2009 9:50 pm
by Christopher
For templates you can also do this:

Code: Select all

<?php foreach ($data as $d) { ?>
   <div id ='some_div'>
   <p>blah blah</p>
   </div>
<?php } ?>
Generally when using PHP as a template language is it used like above. And generally when PHP is being used as an application language echo() is used. Although typically you would gather output into a variable and have a single echo at the end to avoid outputting before any possible headers might be sent.

Re: Basic PHP Design Questions

Posted: Thu May 14, 2009 6:35 am
by allspiritseve
To add to what arborint said, a general best practice in PHP is to include a template like this so you can capture the output into a variable:

Code: Select all

extract ($data);
ob_start();
include ($this->template);
$template = ob_get_clean();
So that template arborint posted could be included, and then $template would contain the output. When you're finally ready to display the page, just echo $template. This works especially well if you have a wrapper template for all of your pages. You can have a section where you paste a variable, say, $content, and just fill it with each page's content.

You may also want to place the above snippet into a simple class that you can set up with data and render.

Re: Basic PHP Design Questions

Posted: Fri May 22, 2009 3:53 pm
by kaisellgren
gdtyra wrote:Since it's within PHP code, do I always need to use echo to render HTML?
Echo sends data to the output buffer, which then appears in the HTTP body part of the response.

Btw, is RoR slow? I have got the impression that it is not..

Re: Basic PHP Design Questions

Posted: Sat May 23, 2009 10:51 pm
by josh
You should consider checking out Zend_Controller + Zend_Layout, it has a partial view helper for breaking up header & footer like you said, and a partial loop helper for externalizing template code inside of loops