Simple MVC Framework With PHP (bootstrapping)
Let’s walk through the creating another PHP framework together! With all the fun stuffs in modern day PHP frameworks, from scratch to finish!
Part 1: Introduction
Copy below code and paste into your .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
# Stop processing if already in the /public directory
RewriteRule ^public/ - [L]
# Static resources if they exist
RewriteCond %{DOCUMENT_ROOT}/public/$1 -f
RewriteRule (.+) public/$1 [L]
# Route all other requests
RewriteRule (.*) public/index.php?route=$1 [L,QSA]
</IfModule>
Your .htaccess fille should look something like this:
Create an app.php file inside the config folder, this file will hold basic app configuration:
copy and paste this code inside:
<?php
define('APP_NAME', "MVC Framework");
define('APP_ROOT', dirname(dirname(__FILE__)));
navigate to the index.php file in you public folder and include the app.php file
<?php
require_once '../config/app.php';
if you did everything properly, you should be able to echo APP_NAME in your index.php file and get “MVC Framework”
Auto-loading:
For the purpose of autoloading classes, we will be using composer
(Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.) credit getcomposer.org
In your root directory create a file and name it composer.json, in this file copy and paste this code:
{
"name": "emiracle/simple-mvc-framework-with-php",
"description": "Simple MVC framework with PHP",
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}
If you don’t have composer installed head over here and install it:
Your composer.json file should look something like this:
psr-4 auto-loading standard is basically a standard in php that attempts to map a path to a particular namespace, this also further guesses this sub folders according to the namespace defined in it
In the image above, the autoloader will automatically look for any file that has a namespace starting with App in the app directory.
Create a “Controller” and “Model” folder in your “app” directory
The resulting folder structure should look something like this:
Now run the below command in your terminal to install composer dependencies:
composer dump-autoload
require the autoload file in your public/index.php
require_once '../vendor/autoload.php';
TESTING THE BOOTSTRAPPING
Write a simple class with a static method that returns the string “bootstrap is working”. as seen in the image below:
now call this method in your index.php as seen below:
If you get a response saying “bootstrap working” kudos! you’re good to go!