BDuelz
BDuelz

Reputation: 3928

Using PHP classes to format html?

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?

Upvotes: 2

Views: 591

Answers (2)

Tom Pažourek
Tom Pažourek

Reputation: 10207

You can use Smarty template engine or something similar.

It's templates are stored separately and look like this: http://www.smarty.net/sampleapp/sampleapp_p5.php

Upvotes: 0

Gambler
Gambler

Reputation:

It's a good practice. Personally, I use the following template "engine":

<?php
class Template{
    static function show($path, $arg = NULL){
        include "templates/$path.php";
    }

    static function get($path, $arg = NULL){
        ob_start();
        self::show($path, $info);
        $block = ob_get_contents();
        ob_end_clean();
        return $block;
    }
}

In your case the template would be like this:

<?php
echo '<h1>'.$arg['user']['userName'].'</h1>'; 
if($arg['showDesc']){
  echo '<div>'.$arg['user']['description'].'</div>'; 
}
?>

You could unpack the array with the template arguments, but I prefer to keep it all in one place, so the code is less confusing. (You always know what is coming from the input, and what's defined in the template this way. To keep things shorter, you might use $_ instead of $arg too.) For a small example like this, the benefit is not obvious, but for larger templates it save a lot of variable manipulation, as you can use PHP's own templating abilities.

Upvotes: 1

Related Questions