Here I will discuss a few ways to organize the code in your web application. Although I cannot present you with every possible way of organizing code, I can at least discuss some of the most common ways.
One Script Serves All
One script serves all stands for the idea that one script, usually index.php,handles all the requests for all different pages. Different content is passed as parameters to the index.php script by adding URL parameters such as ?page=register.
In this application, a specific file and class can handle the request. You can imagine that, in case you have many different modules, the switch case will grow large, so it might be worthwhile to do it dynamically by loading a number of modules from a dedicated directory, like the following (pseudo code):
foreach (directory in "modules/") {
if file_exists("definition.php") {
module_def = include "definition";
register_module(module_def);
}
}
if registered_module($_GET['module']) {
$driver = new $_GET['module'];
$driver->execute();
}
?>
One Script per Function
Another alternative is the one script per function approach. Here, there is no driver script like in the previous section, but each function is stored in a different script and accessed through its URL (for example, about.php, where in the previous example, we had index.php?page=about). Both styles have pros
and cons; in the “one script serves all” method, you only have to include the basics (like session handling, connecting to a database) in one script, while with this method, you have to do that in each script that implements the functionality. On the other hand, a monolithic script is often harder to maintain
(because you have to dig through more files to find your problem).
Of course, it’s always up to you, the programmer, to make decisions regarding the layout of your application. The only real advice that we can give is that you always need to think before you implement. It helps to sit down and brainstorm about how to lay out your code.
Separating Logic from Layout
In each of the two approaches, you always need to strive to separate your logic from the layout of your pages. There are a few ways to do this—for example, with a templating engine like smarty or you can also use your own templating method.
- Kiran's blog
- 690 reads













Post new comment