Part 02 - Front Controller (index.php) File
Source Code Files of this Chapter: project-root/ └── public/ └──index.php # new file Front Controller Design Pattern Front controller is a central (obviously a single) entry point to handle incoming client request. To implement front controller design pattern in this project, our central entry point will be an index.php file. So let's create an index.php file in the public directory. We have…
In this chapter, we explore the Front Controller design pattern, a central entry point for handling incoming client requests in a PHP application. To implement this pattern, we create a file named "index.php" in the "public" directory of our project. We choose this location to protect sensitive project code from public access, which can be enforced through file permissions.
Next, we open the newly created "public/index.php" file and add the following code:
<?php
declare(strict_types=1);
echo "Welcome to the PHP core OOP Project!";
?>
The first line, declare(strict_types=1), enforces strict type checking for function arguments and return values within the file. This means that only the exact type of the type declaration will be accepted, or a TypeError will be thrown. However, it is important to note that declare(strict_types=1) cannot be set globally for the entire project; it must be placed at the top of each PHP file.
The echo statement displays the string "Welcome to the PHP core OOP Project!" on the browser screen.
To test our code, we need to ensure that our local server and domain hosting are properly configured. Assuming the setup is correct, we can browse to our local URL (e.g., http://localhost:8000) to see the expected result: "Welcome to the PHP core OOP Project!". If there are any issues, we can review the error code number and debug accordingly, or check the server log if necessary.
Additionally, we are introduced to the Page Controller architectural approach, which differs from the Front Controller pattern. In the Page Controller approach, each individual page request has its own controller, responsible for handling the logic associated with that specific page or request. While the Front Controller provides a single, centralized entry point for all requests, the Page Controller offers a more granular level of control for individual pages.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.