vendredi 20 mars 2015

Any good design pattern to use for extracting HTML from business login in PHP?

I have an old PHP4 web app in which most of the pages looks like this(some pages has a left menu, some doesn't have a footer):



<?php
echo "<html>";
echo "<head><title>TITLE GOES HERE</title></head";
echo "<body>";
echo "<h2>THIS IS A TITLE</h2>";
// Here i fetch data from DB
echo "<table>";
echo "<tr>";
echo "</tr>";
foreach($rowsFromDB as $row) {
echo "<tr>";
// here i echo some <td> containing $row data
echo "</tr>";
}
echo "</table>";
echo "</body>";
echo "</html>";
?>


This is a simple example, the real ones contains a lot of spaghetti code (i'm italian, i like spaghetti but not in my code) and i'm trying to refactor/redesign it in some way. Rewrite the entire app from scratch (maybe with an MVC framework) is not an option because the app contains a lot of business logic i would like to keep. My idea (for now) is to wrap the echos inside a renderer class, something like this:



<?php
class Renderer {
public static function renderHeader() {
echo "<html>";
echo "<head><title>TITLE GOES HERE</title></head";
echo "<body>";
echo "<h2>THIS IS A TITLE</h2>";
}

public static function renderContent($rowsFromDB) {
echo "<table>";
echo "<tr>";
echo "</tr>";
foreach($rowsFromDB as $row) {
echo "<tr>";
// here i echo some <td> containing $row data
echo "</tr>";
}
echo "</table>";
}

public static function renderFooter() {
echo "</body>";
echo "</html>";
}
}

$renderer=new PageRenderer();
$renderer->renderHeader();
// Fetch data from DB
$renderer->renderResults($rowsFromDB);
$renderer->renderFooter();
?>


The problem with the above solution is that is difficult to extend and maintain. Do you know any design pattern or any technique i could use for a better refactoring/redesign? Thanks in advice and sorry for my bad english


Aucun commentaire:

Enregistrer un commentaire