PHP:MVC - Model View Controller | Front Controller #1 & Routers

Prince

[ Verified Seller ]
Staff member
Trusted Seller
Joined
11 yrs. 6 mth. 27 days
Messages
5,381
Reaction score
18,380
Age
45
Wallet
11,590$
Now that we are done with the Application class, Loader and Config mechanisms, we can proceed to the building of our front controller. The front controller is what initiates our whole framework. It's the very beginning of the system. So let's see how we will structure and code it.

Code:
Please, Log in or Register to view codes content!
We need one public method which we'll call dispatch() and upon calling it, the controller needs to find which router to use then make an instance for it and the other process is within the router. First we need one private property which will hold the controller and a method in the run class of our App.file.

Code:
Please, Log in or Register to view codes content!
And now we need to make an instance in run():

Code:
Please, Log in or Register to view codes content!
There a lot of things around that but for now, we just make an instance for it and call dispatch(). We need to have that implementation of the front controller in the run class because if it's in the construction we'll have some trouble in the future. Everything will be explained further in the series. The dispatch() method will determine which controller to use. Imagine we have some cron job on our server that calls the system from command line. We won't even have HTTP protocol then. So here is the perfect place to explain about the routers. Each one of them is responsible for a certain matter. One for JSON requests, one for command line requests and so on.

Code:
Please, Log in or Register to view codes content!
Just to make sure it all works, let's hardcore the Front controller file a bit:

Code:
Please, Log in or Register to view codes content!
We end up with the output:

Code:
Please, Log in or Register to view codes content!
Resulting in:

Code:
Please, Log in or Register to view codes content!
Now we can extract that address from REQUEST_URI with a simple str_replace function. However, note that under IIS, PHP_SELF is not returned, therefore stick to REQUEST_URI. Either ways they both do the same job.

Code:
Please, Log in or Register to view codes content!
 
Top Bottom