iotegui iotegui - 1 month ago 11
HTML Question

Is it correct to print long HTML via PHP?

I would like to know if it is correct to print long html through php classes with echo instead of just print it in a normal way, for example do the following:

Supose i have an user class

User.php

class User {

private $name, $age;

public function __construct($name, $age) {

$this->name = $name;
$this->age = $age;

}

public function printProfile($name, $age) {

echo '<div class="panel panel-profile">

Name: '.$this->name.'<br />
Age: '.$this->age.'<br />
</div>';
}
}


And my profile.php would look something like

profile.php

<html lang="en">

<head>

<?php

require_once __DIR__ . "/Head.php
$head = new Head();
$head->printPanel();

?>

</head>

<body>
<?php

require_once __DIR__ . "/Header.php
$header = new Header();
$header->printPanel();

?>
<div class="content">

<?php

require_once __DIR__ . "/User.php
$user = new User();
$user->printProfile();

?>
</div>
<?php

require_once __DIR__ . "/Footer.php
$footer = new Footer();
$footer->printPanel();

?>
</body>
</html>


So.. I know it's possible but i don't know if is it correct to do that, am i making a proper use of the code? will influence the processing speed?
I like this way because i can reduce the code in all the pages, and just by changing the class it modify all the code. I also know that i could make something like

<?php require_once __DIR__ . "/header.php ?>


And include all the code there without making a class

header.php

<header>

some stuffs

</header>


But i don't really like this because it is not object-oriented.

Sorry about my english as you may have noticed i'm not really good at it.

Answer

Turns out, object orientation isn't everything. If you can do just as much procedurally, do it. In your case, for a simple website, you can get away with storing all of your chunks in a separate file, say, Chunks.php. Use one function for each of the pieces you want to add. You don't need 20 different classes with constructors for each element on the page. Just use static methods.

As for code style, put all your requires at the top so your page doesn't crash half way through rendering:

<?php require_once __DIR__ . "/Chunks.php ?>

<html lang="en">

    <head>
        <?php Chunks::printHead(); ?>
    </head>

    <body>
        <?php Chunks::printHeader(); ?>
        <div class="content">
           <?php Chunks::printUserProfile(); ?>
        </div>
       <?php Chunks::printFooter(); ?>
    </body>
</html>

Simple, easy to read, and does exactly what you expect without 30 different 20-line files clogging up your view.