π Introduction: Why Build Your Own Simple PHP Framework?
Have you ever gazed in awe at frameworks like Laravel or Symfony and thought, “How do they even work?” π€ You’re not alone! Building your own simple PHP framework is not only an amazing way to understand the inner workings of these giants, but itβs also a chance to flex your coding muscles πͺ and take your PHP skills to the next level.
In this guide, weβll create a lightweight PHP framework step-by-step. Think of it as the ultimate DIY project, featuring essentials like:
- Routing (because we all hate typing
index.php?page=something
π), - Controllers (to keep your logic tidy), and
- Views (to make things look pretty πΌοΈ).
Whether you’re a beginner or a seasoned dev looking to refresh your skills, this tutorial will walk you through creating your very own simple PHP framework. Letβs dive in! π
π Step 1: Setting Up Your Simple PHP Framework
First, we need a solid foundation. Start by creating a folder structure for your framework.
Folder Structure
Hereβs the layout for your simple PHP framework:
my-framework/
βββ public/
β βββ index.php
βββ src/
β βββ Router.php
β βββ Controller.php
β βββ View.php
β βββ routes.php
βββ composer.json
public/
: Contains the entry point for the framework (likeindex.php
).src/
: Houses core framework files such as the router, controller logic, and views.composer.json
: Manages autoloading and dependencies.
This is the skeleton of your simple PHP frameworkβlightweight but powerful! πΌ
βοΈ Step 2: Initializing Composer (The Unsung Hero)
Modern PHP projects rely on Composer for autoloading. Itβs like having a personal butler for your classes. π΄οΈ
Run the following in your terminal:
composer init
Add an autoload section to composer.json
:
{
"autoload": {
"psr-4": {
"MyFramework\\": "src/"
}
}
}
Then, generate the autoloader:
composer dump-autoload
With this, your classes from the src/
directory are magically loaded whenever you need them. β¨
πͺ Step 3: Create the Entry Point
The heart of your simple PHP framework is the entry point: public/index.php
. All incoming requests will funnel through this file.
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use MyFramework\Router;
$router = new Router();
// Include routes
require_once __DIR__ . '/../src/routes.php';
// Dispatch the current request
$router->dispatch($_SERVER['REQUEST_URI']);
Boom! π₯ Your simple PHP framework is ready to process requests.
π£οΈ Step 4: Building the Router Class
Routing is where the magic happens! β¨ The router directs requests to the correct controller or function.
File: src/Router.php
<?php
namespace MyFramework;
class Router
{
private $routes = [];
public function get($path, $callback)
{
$this->routes['GET'][$path] = $callback;
}
public function post($path, $callback)
{
$this->routes['POST'][$path] = $callback;
}
public function dispatch($uri)
{
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($uri, PHP_URL_PATH);
if (isset($this->routes[$method][$uri])) {
$callback = $this->routes[$method][$uri];
if (is_callable($callback)) {
call_user_func($callback);
} elseif (is_string($callback)) {
$this->invokeController($callback);
}
} else {
http_response_code(404);
echo "404 Not Found π’";
}
}
private function invokeController($controller)
{
list($class, $method) = explode('@', $controller);
$class = "App\\Controllers\\$class";
if (class_exists($class) && method_exists($class, $method)) {
$controller = new $class();
$controller->$method();
} else {
echo "Controller or method not found. π";
}
}
}
Now, your simple PHP framework can handle routes like a pro. π£οΈ
π§ Step 5: Creating a Base Controller Class
Controllers keep your logic neat and separate from views.
File: src/Controller.php
<?php
namespace MyFramework;
class Controller
{
public function view($name, $data = [])
{
extract($data);
require_once __DIR__ . "/../views/$name.php";
}
}
π Step 6: Setting Up Routes
Define your appβs routes in src/routes.php
.
<?php
use MyFramework\Router;
$router->get('/', function () {
echo "Welcome to My Simple PHP Framework! π";
});
$router->get('/about', 'PageController@about');
π©βπ» Step 7: Creating Controllers
Controllers bring functionality to your routes.
File: src/Controllers/PageController.php
<?php
namespace App\Controllers;
use MyFramework\Controller;
class PageController extends Controller
{
public function about()
{
$this->view('about', ['title' => 'About Us']);
}
}
πΌοΈ Step 8: Crafting Views
Views are HTML templates that make your app shine.
File: views/about.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $title ?></title>
</head>
<body>
<h1><?= $title ?></h1>
<p>Welcome to the About page of this simple PHP framework! π</p>
</body>
</html>
π Step 9: Running Your Simple PHP Framework
Fire up your PHP server:
php -S localhost:8000 -t public
Visit http://localhost:8000 to see your simple PHP framework in action. π
π οΈ Expanding Your Framework
Now that youβve built the basics, consider adding:
- Middleware for pre-processing requests.
- Database support with PDO or an ORM.
- Error handling and custom 404 pages.
- Advanced routing with parameters like
/user/{id}
.
Using Your Custom Simple PHP Framework to Build an App
Now that youβve laid the foundation of your very own simple PHP framework, itβs time to put it to work! πͺ Letβs build a small application that includes a homepage, an about page, a contact form, and even dynamic URL routing. By the end of this, youβll see how versatile and powerful your simple PHP framework really is. π
π Step 1: Create a Homepage Route
Whatβs an app without a homepage? Letβs make your framework welcome visitors with open arms. π‘
In src/routes.php
, define a route for the homepage:
<?php
use MyFramework\Router;
$router->get('/', function () {
echo "<h1>Welcome to My Custom PHP Framework! π</h1>";
echo "<p>Start building your application with ease. π</p>";
});
π― Try it out:
Visit http://localhost:8000 in your browser, and youβll see your shiny new homepage! Itβs the first step in transforming your simple PHP framework into something extraordinary. π
π Step 2: Add an About Page
A good application should tell people what itβs all about, right? Letβs build an About page that leverages your controllers and views.
In src/routes.php
, add a route for the about page:
$router->get('/about', 'PageController@about');
Now, create the controller file src/Controllers/PageController.php
:
<?php
namespace App\Controllers;
use MyFramework\Controller;
class PageController extends Controller
{
public function about()
{
$this->view('about', ['title' => 'About Us']);
}
}
Finally, letβs create the corresponding view in views/about.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $title ?></title>
</head>
<body>
<h1><?= $title ?></h1>
<p>Welcome to the About page of our custom simple PHP framework! π</p>
</body>
</html>
π― Try it out:
Visit http://localhost:8000/about, and enjoy your fully functional About page! With the help of your simple PHP framework, youβve seamlessly connected routing, controllers, and views. π
βοΈ Step 3: Add a Contact Page with a Form
No web app is complete without a way for users to get in touch! Letβs add a Contact page with a form for user input.
In src/routes.php
, define the routes:
$router->get('/contact', 'ContactController@showForm');
$router->post('/contact', 'ContactController@handleForm');
Create the controller file src/Controllers/ContactController.php
:
<?php
namespace App\Controllers;
use MyFramework\Controller;
class ContactController extends Controller
{
public function showForm()
{
$this->view('contact', ['title' => 'Contact Us']);
}
public function handleForm()
{
$name = $_POST['name'] ?? 'Guest';
$message = $_POST['message'] ?? 'No message provided';
echo "<h1>Thank You, $name! π</h1>";
echo "<p>Your message: $message</p>";
}
}
Now, create the form view in views/contact.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $title ?></title>
</head>
<body>
<h1><?= $title ?></h1>
<form action="/contact" method="post">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" required>
<label for="message">Your Message:</label>
<textarea name="message" id="message" required></textarea>
<button type="submit">Send</button>
</form>
</body>
</html>
π― Try it out:
Visit http://localhost:8000/contact to see your form in action. Submit the form and watch as your simple PHP framework processes the input like a champ! π
π Step 4: Add Dynamic URL Parameters
Dynamic routing adds flexibility and functionality to your app. Letβs create a route that greets users by ID.
In src/routes.php
, add this dynamic route:
$router->get('/user/{id}', 'UserController@profile');
Create the controller src/Controllers/UserController.php
:
<?php
namespace App\Controllers;
use MyFramework\Controller;
class UserController extends Controller
{
public function profile($id)
{
echo "<h1>Welcome, User #$id! π</h1>";
}
}
π― Try it out:
Visit http://localhost:8000/user/42, and see your dynamic routing come to life. Your simple PHP framework is now capable of handling complex URL structures. π
π‘οΈ Step 5: Adding Middleware (Optional but Cool)
Want to add more power to your framework? Middleware is the way to go. Letβs add an authentication check for a restricted page:
In src/routes.php
:
$router->get('/admin', function () {
if (!isset($_SESSION['user'])) {
echo "Unauthorized π«";
return;
}
echo "Welcome to the admin panel! π";
});
This snippet shows how you can use middleware-like logic in your routes. Your simple PHP framework just keeps getting better! πͺ
π Conclusion: Your Simple PHP Framework in Action
π You did it! Youβve not only built a simple PHP framework from scratch, but youβve also created a functional web application with routing, controllers, views, dynamic parameters, and even middleware.
Your framework is lightweight, versatile, and ready for action. π Whether youβre building a personal project, experimenting with new ideas, or just sharpening your PHP skills, this simple PHP framework is a fantastic tool in your arsenal.
The journey doesnβt stop here! Expand your framework with:
- Database integration for dynamic data storage.
- Error handling to make debugging a breeze.
- Advanced routing for more complex URLs.
The possibilities are endless. So, what will you build next with your simple PHP framework? The world is your playground! π
If you have any questions or suggestions do comment down below ππ, check out PHP CRUD API Generator: Generate Your Own Dynamic API if your are new to PHP or check out generic-crud-api-in-php if you want to learn how to create API’s in PHP
Thanks for Reading β€οΈβ€οΈππ