I have recently begun building webpages using PHP, and being inexperienced, I have a question about coding conventions.
Is it considered bad style to use require to dynamically load page content or page elements in a web page?
For example, if you are modularizing your code, and have a /resources/pageContent/ folder with different files containing the content of different pages. Would it be considered bad style to say require ("resources/pageContent/profile.php")?
Another way I’ve seen this done is using fopen(), but of course, it won’t allow you do use any PHP code in your dynamically loaded pages and will only print the HTML and CSS.
I am just trying to put things into modules, since putting things in functions (For example, loadPageProfile) can get really messy-looking.
First of all,
If you want to write clean and maintainable code, DO NO USE error suppressor
@Listen to all errors – big and small ones. This will help you greatly. Really.
When you’re done, then just change
Well, then you’re getting on a right track…
All you gotta do is to create one module called, like,
Page. (we are talking about pages now)It’s bad practice to use procedual code to create the modules since we are talking about them.
Just encapsulate all logic into a class, like this:
File
Page.phpNow assume that you have pages:
contact,index,profile,login,registerSo instead of usingrequire()everywhere you simply call that “comfortable” method.While, the footer and menu could be similar to this ones:
File: footer.phtml
File: menu.phtml
To require particular class you can create, some
module, like this one, as well:Then when you need particular class, just call
And please remember, when we talk about Modules, in 99% cases we talk about classes that has its implementation within this one.
Another advices, would be:
1) Do no mix CSS with HTML (create separated css file and include it on particular page, via
<link href="path_to_css.css" rel="stylesheet" type="text/css" />Because it makes markup clear and easy to maintain in future (say when you want to change the style or add something)
2) Do not mix PHP and JavaScript code. Keep JavaScript files in separated files as well as CSS. Use Ajax to share variables between PHP and JavaScript
3) Do not mix them all HTML,CSS,JavaScript with PHP. Especially HTML. Keep that
modules(classes or business logic) in separated files. Then just include the part you need for particular task.