Is there a way to separate PHP Code and HTML?

I need to separate PHP code and HTML. Is there a way to do this?

Comments

  • To separate your PHP code and HTML as much as possible you need a small template class and a small set of rules to follow.

    Function calls should only be made to render templates or format data like date().
    Only use foreach, no for or while loops.
    if statements should only check a variable for true. All boolean logic should be pre-computed.
    Using else is OK.
    
    If you need to alternate a color, either pass boolean values with your array for each row or use ($i++%2). Then in your view you will use an inline if:
    
    <div class='menu <?=($link['alternate'])?'white':'grey'?>'>
    
    If you need to check for the beginning or end of a list, pass a flag in the associate array that you're currently iterating through.
    

    To make simple or advanced web site you need something that can hold data and a file path. With the below classes you create a new Template object and bind some data to it as it is created.

    $main = new Template('mainView.php', array('title' => 'example page'));

    Now in your view file mainView.php you access the title like this.

    <?= $title; ?> // php 4 version
    <?= $this->title; ?> // php 5 version

    The reason you use an object instead of just an include file is to encapsulate data. For example:

    $main = new Template('mainView.php', array(
    'title' => 'example page',
    'leftMenu' => new Template('linkView.php', array('links' => $links)),
    'centerContent' => new Template('homeView.php', array('date' => date())),
    ));

    $main->render();

    mainView.php



    <?= $this->title; ?>


    <? $this->leftMenu->render(); ?>

    <? $this->centerContent->render(); ?>


    Below are minimal template classes for both php 4 and 5.

    // PHP 4
    class Template {
    var $args;
    var $file;

    function Template($file, $args = array()) {
        $this->file = $file;
        $this->args = $args;
    }
    
    function render() {
        extract($this->args);
        include $this->file;
    }
    

    }

    // PHP 5
    class Template {
    private $args;
    private $file;

    public function __get($name) {
        return $this->args[$name];
    }
    
    public function __construct($file, $args = array()) {
        $this->file = $file;
        $this->args = $args;
    }
    
    public function render() {
        include $this->file;
    }
    

    }

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion