Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding html in php class file

Tags:

php

class

I have a calendar class which outputs a HTML table with a table cell representing a day of the month, however should I be embedding HTML into a class file. My concern is that if I ever have to amend the HTML (i.e add an ID to an element), then I would have to adjust the class file.

I currently dont use the MVC pattern in my project so having a view is not an option.

My cut down class files is as follows (for this example I have assumed that 1 month is 4 weeks):

class calendar {

function __construct(){

}

function output() {
    print "<table>";
    for ($week=0; $week < 4; $week++) {
        print "<tr>";
        for ($day=0; $day < 7; $day++) {
            print "<td></td>";
        }
        print "</tr>";
    }
    print "</table>";
}

Are there any other methods which I haven't thought about which would keep the HTML separate from the class file Thanks in advance

like image 379
phpNutt Avatar asked May 25 '11 11:05

phpNutt


3 Answers

The most simple templating

// myTemplate.phtml
<div><?php echo $xy; ?></div>

// SomewhereElse.php
class MyClass {
  public function myMethod () {
    $xy = 'something';
    include('myTemplate.phtml');
  }
}
like image 148
KingCrunch Avatar answered Oct 07 '22 09:10

KingCrunch


One very popular solution for your problem is to use http://www.smarty.net/ or order template engine in order to split your presentation logic from business logic.

like image 44
gsone Avatar answered Oct 07 '22 10:10

gsone


You could have some sort of HTML helper class that generates your code. The class can have createTable, addRow, closeTable, createForm, addField, etc.. The main properties are sent in the method call, and the constants are coded directly into the HTML.

like image 36
dee-see Avatar answered Oct 07 '22 10:10

dee-see