- May 30, 2013
- by Brad Litwin
I’m surprised whenever I look at recently written PHP and see folks are still writing their HTML inline with their code. Perhaps it’s because so many PHP tutorials teach this style, or maybe people just aren’t aware of the advantages of separating it out. If you still write this way, feel free to comment on why. I’ll try to explain the advantages of separating it out here. I won’t get into the details of Model-View-Controller programming here, see that Wikipedia article or a blog post I will probably eventually do about it. But for now I will just plead that you separate out your display HTML from your functional PHP code.
The easiest way to understand why HTML and functional code should be separated out is to think of your HTML as another function. Separating out your code into individual functions based on their behavior and use makes obvious logical sense. Similarly, your HTML is serving a separate purpose from the code that populates the data it’s displaying. The HTML is display formatting code. The habit of putting your HTML inline with your PHP is based on thinking of either the PHP in little snippets that happen within the page, or thinking of the HTML as though it is string data whose syntax is somewhat irrelevant to the surrounding code. Both approaches are failing to respect the purpose and function of one or more parts of your program.
When you break out your HTML into a template file, you are respecting the HTML to fulfill its role and your PHP code to fulfill its role, and above all respecting any future developers who inherit your project.
Changes made to the PHP may not necessitate changes made to the HTML, and visa versa. So having them together in a single file is creating an unnecessarily complex situation which could be much more elegant and simple if it were simply separated out.
Even if your script is so small and simple that using even the smallest template engine doesn’t make sense, at a minimum your HTML and display code should be separated into its own functions or methods. This will allow both your functional code and your display code to be more easily maintained and updated in the future.
If you’re looking for a high performance home for all of your PHP development, make sure to visit A2 Hosting. Our accounts are blazing fast and offer you your choice of PHP versions.