Is it bad practice using require() a lot? Most websites have a header and a footer that looks the same whereever you navigate on the page. But the main content varies from page to page. And since I don´t want to reuse code, have the same code in two places, I think require() is pretty good. But is it okay using it like I do?
Here´s my example:
<div class="content">
<section>
<?php require('mainpage.php'); ?>
</section>
<aside class="sidebar">
<div class="sidebar-box">
<?php require('sidebar/box1.php'); ?>
</div>
<div class="sidebar-box">
<?php require('sidebar/box2.php'); ?>
</div>
</aside>
</div>
A sidebar box is a box that contains stuff like “Latest news” etc. And since I may want to have the “Latest news” box on many pages I need to require() it in order to not have the same code in two places.
Should I solve it someway else?
Thanks for your help!
Nothing wrong with that at all, it’s very good practice to reuse code chunks. It also keep the HTML structure far more readable and gives you some basic separation between HTML presentation and PHP business logic. Check out the MVC pattern for why this is a good thing.
Some points to bear in mind: