Forum Moderators: coopster

Message Too Old, No Replies

Using PHP classes to format html?

Is it a good idea to use OOP to format html

         

megaman732

3:54 am on Aug 15, 2009 (gmt 0)

10+ Year Member



I have a class designated for a certain site. In that site I have different functions to retrieve data from the database and store that data into an array. I have other functions within the same class that take the data and format it into html and returns the html containing the data from the database.

For example...

function GetUserProfile($userID){

$query = 'SELECT * FROM users WHERE userID='.$userID;
.......
blah blah blah
.......
$user = mysqli->fetch_assoc();

return $user;

}

function FormatUserProfile($user, $showDesc = 'false'){
$profile = '<h1>'.$user['userName'].'</h1>';
if($showDesc){
$profile .= '<div>'.$user['description'].'</div>';
}
return $profile;
}
...
So if i had a function to solely gather information, and another function to solely format that gathered information.
Mainly because I will be showing the same data on different pages, but Different pages show different data, like a search would only bring up the users name, where as the users profile page would bring up the username and the description for example.

Is that good practice, or is there a better way to do this?

eelixduppy

3:49 am on Aug 19, 2009 (gmt 0)



It is generally not a good idea to format the data at all within a class. Personally I would use a templating system (ie Smarty) to do something like this.

So for example, let's say you have data that you get back from a database query, you could do something like this:


$smarty->assign('results', $obj->fetchData());

And then when you are ready to print that data in a formatted way, you would use a template file that could look something like the following:


<ul>
{foreach from=$results item=result}
<li>{$result}</li>
{/foreach}
</ul>

And now it would print the data in a nice list. Then if you needed the same data on a different page displayed differently, you can do this, using another template similar to the one above.

In any case, it doesn't have to be Smarty that you use, but I prefer, IMO, to separate the "data" from the "formatting".

Pico_Train

6:23 pm on Aug 19, 2009 (gmt 0)

10+ Year Member



I agree. Savant templating is also good, just an alternative to Smarty. Your choice...