Home arrow PHP arrow Page 4 - JV’s Power Tips for PHP (1)
PHP

JV’s Power Tips for PHP (1)


In this article Justin provides some tips for improving our PHP applications such as a very simple but effective template technique.

Author Info:
By: Justin Vincent
Rating: 3 stars3 stars3 stars3 stars3 stars / 3
January 29, 2003
TABLE OF CONTENTS:
  1. · JV’s Power Tips for PHP (1)
  2. · Never Breaking Out of PHP
  3. · Basic Template Theory
  4. · Refining the Previous
  5. · Accessing Other Variables from Within this Type of Template
  6. · Using Objects to Store Multiple Output Values
  7. · Conclusion

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
JV’s Power Tips for PHP (1) - Refining the Previous
(Page 4 of 7 )

What I have shown so far is the concept of using templates in the most basic form. There are, however, some further refinements that can be made. Let's take another look at the simple template used previously:

<?php

print <<<END
<html>
  <head>
    <title>Simple Template</title>
  </head>
  <body>
    $gBODY
  </body>
</html>
END;

?>


This can work quite well when you are starting out in PHP and if you are a loan developer… but when you start building websites with other people, designers etc., some of whom have no idea how to code PHP it makes sense to abstract this out even further. The ideal solution would be if the above template looked like this:

<html>
  <head>
    <title>Simple Template</title>
  </head>
  <body>
    $gBODY
  </body>
</html>


In other words… a bog standard HTML file that you can put PHP variables in.

Ok rewind. Let’s just get back to the reason why this is a good practice. What are we trying to accomplish with all this? Why is it good to never break out of PHP tags and use templates?

What we are trying to do is to separate HTML from PHP programming logic. This means that:
  1. When you create your site you can put all of your HTML in one place and all your PHP in another.
  2. It means that 2 years down the line when someone says to you the font is the wrong colour in the shopping basket screen (and please can you change it). You don’t have to wade through line after line of HTML embedded in print statements in order to find the part to change. You can simply open up the file templates/shopping_basket.htm (or better still you can get the designer to open it up).
  3. It means that when you work with designers they don’t have to rely on you to make cosmetic tweaks and changes.
      Now that we have re-capped the reasons why all this is useful, lets have a look at a more complex function that will allow us to make use of standard HTML templates with embedded PHP variables (and no PHP tags or print statements).

      <?php

        // This function is stored in functions/global.php

        function get_template($the_template)
        {
          // Make sure that all global variables are available to this functions..
          foreach ( $GLOBALS as $key => $val )
          {
            global ${$key};  
          }
          
          // Make sure the template exists..
          if ( is_file("templates/$the_template.htm") )
          {

            // Load the template into memory (inc. older versions of PHP)
            foreach( file("templates/$the_template.htm") as $line )
            {
              $content .= $line;
            }

            // Convert all the php variables to their dynamic values..
            eval("\$str = \"" . str_replace("\"","\\\"",$content) . "\";");
            
            // Return the merged template from this function..
            return $str;
          }
          else
          {
            echo "Could not find template: $the_template";   
          }
        }

      ?>


      Even though this new function looks quite complicated it is no harder to use than the previous function use_template(); The key difference is that instead of outputting the template contents to the browser it uses the function’s return operator. This gives us the choice of re-assigning the merged template contents, or outputting them to the browser. Here is an example of how useful this is:

      Firstly lets create two templates:

      1) Simple Table Template (simple_table.htm)

      <table>
        <tr>
          <td>
            $dynamic_text
          </td>
        </tr>
      </table>


      2) Simple Main Page Template (simple_template.htm)

      <html>
        <head>
          <title>Simple Template</title>
        </head>
        <body>
          $gBODY
        </body>
      </html>


      Then using a separate PHP script we can output these templates using injected dynamic values:

      <?php

        // Include our growing function library..
        include_once “global/functions.php”;

        // Assign some dynamic text within PHP..
        $dynamic_text = “I Have Loved Turkeys”;

        // Inject this text into the simple table template..
        $merged_table = get_template(“simple_table”);

        // Add the merged table to the main body..
        $gBODY = $merged_table;

        // Inject the main body variable into the main template..
        $complete_page = get_template(“simple_template”);

        // Output complete page to the browser..
        echo $complete_page;
      ?>


      In truth, the above example makes a meal of the task at hand. You can actually do the same thing with much less code (using our global function library). Here’s how:

      <?php

        include_once “global/functions.php”;

        $dynamic_text = “Hello Turkey!”;

        // Inject text into table template and assign to var. gBODY..
        out(get_template(“simple_table”));

        // Inject gBODY into main template and output everything..
        echo get_template(“simple_template”);

      ?>


      If you find yourself confused at this point just go back over this article from the beginning up until this point (you can skip the turkey intro). Make sure you trace through the logic step by step. It may take one or two passes but in the end it will all make sense.
      blog comments powered by Disqus
    PHP ARTICLES

    - Removing Singletons in PHP
    - Singletons in PHP
    - Implement Facebook Javascript SDK with PHP
    - Making Usage Statistics in PHP
    - Installing PHP under Windows: Further Config...
    - File Version Management in PHP
    - Statistical View of Data in a Clustered Bar ...
    - Creating a Multi-File Upload Script in PHP
    - Executing Microsoft SQL Server Stored Proced...
    - Code 10x More Efficiently Using Data Access ...
    - A Few Tips for Speeding Up PHP Code
    - The Modular Web Page
    - Quick E-Commerce with PHP and PayPal
    - Regression Testing With JMeter
    - Building an Iterator with PHP

    Dev Articles Forums 
     RSS  Articles
     RSS  Forums
     RSS  All Feeds
    Weekly Newsletter
     
    Developer Updates  
    Free Website Content 
    Contact Us 
    Site Map 
    Privacy Policy 
    Support 



    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
    Popular Web Development Topics
    All Web Development Tutorials