Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split php content in multiple files

I have no idea if there's a technical term for this, so I didn't find anything on google nor this site.

A friend of mine who has been making sites for years, and actually set up a bussiness, uses a rather unique (to me) system.

He splits up his page into 3 parts, the header, body and footer. Puts them into 3 files, and then includes the header and footer in the body page, leaving only this: (example)

<?php   include_once "Constants/Header.php";    ?>

        <div id="Container">
            <div id="Header">
                HEADER
            </div>

            <div id="Menu">
                <ul id="Nav"> 
                    <li>Menu item</li>  
                    <li>Menu item</li> 
                    <li>Menu item</li>  
                    <li>Menu item</li> 
                    <li>Menu item</li>  
                    <li>Menu item</li> 
                </ul> 
            </div>

            <div id="Body">

            </div>
        </div>

<?php   include_once "Constants/Footer.php";    ?>

Is it good practise to code a site this way? -if so, why? And last but not least, do you code your pages this way?

like image 925
Nick Avatar asked Nov 09 '10 14:11

Nick


1 Answers

As several others have mentioned, splitting your code up into multiple PHP files can help you avoid duplicating your work unnecessarily. However, an even bigger benefit that can fall out of this is that the include statement is the gateway to providing is implementing a sitewide architecture such as Model-View-Controller.
Using MVC, your code is split up not just in terms of parts of the page that the user sees (header, footer, body, etc), but also in terms of responsibility. At a high level, the "Model" manages the data and business logic, the "View" handles the user interface (including rendering data from the model), and the "Controller" handles requests and interacts with the appropriate parts of the Model.
I'm no expert on MVC by any means, but the benefits here are enormous. Each of the components can be tested individually. Designing the components to be "loosely coupled" helps you avoid repeating yourself and encourages writing reusable code. There are a number of PHP web application frameworks that use MVC architecture, many of which are freely available (e.g., CodeIgniter).
Admittedly, MVC is not necessarily the "one true way" -- in your friend's case, implementing an architecture like this may be outside of the scope of what he wants to do. But in regards to your original question (in a roundabout sort of way I guess), the include statement can (when used properly) be a very powerful and useful tool.

like image 139
Donut Avatar answered Oct 18 '22 20:10

Donut