Simple MVC Framework With PHP (Request Parsing)

Chibuzo Miracle
2 min readAug 28, 2022

--

In this module, we will try to create a replica of Laravel’s way of calling the request class in a controller. By the end of this module, we aim to achieve the code sample below.

To achieve the above we will have to make an alteration to out UrlEngine.php and replace line 13 with this:

return strtok($_SERVER["REQUEST_URI"], '?');

The reason we have to do this is to make sure we separate the query string from the URL.

Now create a class called Request.php in your bootstrap folder. It should look something like below:

Now lets break this class down:

One: we are using stdClass as we wish to pass around data as objects, come on! let’s honor the name “OOP” at least.

Two: The construct initializes data as a new object and calls the set data method.

Three: the setData method is responsible for loping through all post and get request, do primary sanitization on it and not only will we calls it dynamically but we will also populate the data object.

NB: we would have just gone ahead to use the $_REQUEST global but using it would put us in a tricky situation when wanting to sanitize automatically. you can go ahead and give it a try for education purposes.

Now we would have to make modifications to our Framework.php file to accommodate the request class when instantiating a method.

Your new Framework.php file should look like this:

We instantiated the Request class in a construct in our Framework.php file and also passed the instantiated request to the method automatically while calling the method on line 38. The reason is to prevent the too few argument supplied error that PHP will throw.

With these done success fully, you can not only access the request query or body like laravel, but you can also access a bag (data()) containing all request parameters.

Follow for more!

Thanks for getting to the end of the article!

--

--

Chibuzo Miracle

B Eng A&B Engineering || Software Developer || Technical Writer