Using PHP include to separate site content

前端 未结 4 634
梦毁少年i
梦毁少年i 2020-12-03 16:17

I\'m looking for advice on the best practice for separating site content up into logical blocks. I want a header and footer that are constant throughout the site, so that if

4条回答
  •  情话喂你
    2020-12-03 16:58

    Nope, your approach is wrong.
    Here are main faults in your design:

    1. You're assuming that header.php would be called on the every page call. That's wrong.
    2. You're assuming that header.php will always be static. That's wrong.
    3. You forgot to create a template for the page itself.

    The main rule everyone have to learn by heart:

    Not a single character has to be sent into browser, until all data gets ready.

    Why?

    • it's 2011 today. AJAX era. What if your code will have to send JSONed data instead of whole HTML page?
    • there is a thing called HTTP header. Sometimes we have to send them. And it's gets impossible if you already have your ornate HTML header sent.
    • it's for just 4-page site. Okay. Imagine you've got lucky and got a request for another 4-page site. You will have to change only templates and don't touch engine files. That's really great benefit.
    • Imagine you're going to make a custom </code> tag for your pages, based on the page content. Isn't it extremely common thing? But you can't make it without using templates. </li> </ul> <p>So, you have to have one common site template containing header and footer and also dedicated templates for the every php script.</p> <p>An example layout is going to be like this:</p> <p>.1. page itself. </p> <p>it outputs <strong>nothing</strong> but only gather required data and calls a template:</p> <pre><code><?php //include our settings, connect to database etc. include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php'; //getting required data $DATA=dbgetarr("SELECT * FROM links"); $pagetitle = "Links to friend sites"; //etc //and then call a template: $tpl = "links.tpl.php"; include "template.php"; ?> </code></pre> <p>.2. <code>template.php</code> which is your main site template, </p> <p>consists of your header and footer:</p> <pre><code><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>My site. <?=$pagetitle?>

      .3. and finally links.tpl.php is the actual page template:

      easy, clean and maintainable.

提交回复
热议问题