This week I worked on creating an php MVC framework from scratch.
MVC pattern is what php frameworks such as Laravel are based on. M stands for models and handles all the requests to the database. Generally one model handles requests made to a table in the database. V stands for View. View is the frontend of the project and manages the frontend display and html. C stands for Controller. The Controller controls which view gets displayed and what gets sent to the model. The POST, GET request ect are handled by the Request class and then sent to the controller. The controller is a class that has methods named as actions. Those actions determines what view is displayed and what data gets sent a the model.
I have been working on setting up a small site using the MVC framework.(GitHub link) I learnt some more complicated regular expressions for routes to handle variables and for those be converted to regular expressions such that /controller/:id/action, or /controller/action could be matched to the url. For example /posts/edit would be matched to a regular expression so that the data would be sent to the controller Posts and the action edit. The url /posts/12/edit would go to the controller Posts and the action edit and the id of 12 will all be passed to the controller.
I learn about how to use abstract classes so that the child classes inherit methods and properties of its abstract parent. Also I learnt the efficiency of using static properties and methods. As an example, having a class that handled database connection you can have a static method that connects to the database. Therefore all instances of the class can connect to the database as the method is associated to the class not the instance. As a result resources are not being used up with repeated calls the the database.
I focused some time on errors and exceptions in php 7. How you can handle errors and exceptions and how you can create user created errors / exceptions. You can create your own exception class that extends from the php Exception class and customise your handling of errors. I learnt about stack trace and how in php its a stack is handled on a ‘first in first out’ basis. So if you have a hierarchy of error classes, it first goes to the child catch and if its not caught there will go the its parent and so on.