A custom framework is a common requirement in web development. By building your own framework, developers can better meet project requirements and improve development efficiency. This article will show you how to build a simple custom framework in PHP.
A typical PHP framework should include the following components:
Next, we will implement a custom framework step by step based on the above structure.
The router determines which controller and action correspond to a given URL.
class Router { protected $controller = 'DefaultController'; protected $action = 'indexAction'; public function handleRequest() { $url = $_SERVER['REQUEST_URI']; // Parse URL to get controller and action $parts = explode('/', $url); if (isset($parts[1]) && !empty($parts[1])) { $this->controller = ucfirst($parts[1]) . 'Controller'; } if (isset($parts[2]) && !empty($parts[2])) { $this->action = $parts[2] . 'Action'; } // Create controller object and call the corresponding method $controller = new $this->controller(); $controller->{$this->action}(); } }
The controller receives and processes the request, then calls the model and view to complete the operation.
class DefaultController { public function indexAction() { echo 'Hello, welcome to my custom framework!'; } }
The model handles interactions with the database and performs CRUD operations. In this example, we will not perform database operations, but simply provide a basic method.
class UserModel { public function getAllUsers() { return [ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ['id' => 3, 'name' => 'Charlie'], ]; } }
The view is responsible for displaying the data and showing it to the user.
class View { public function render($data) { foreach ($data as $item) { echo 'ID: ' . $item['id'] . ', Name: ' . $item['name'] . '<br>'; } } }
require_once 'Router.php'; require_once 'Controller.php'; require_once 'Model.php'; require_once 'View.php'; $router = new Router(); $router->handleRequest();
Save the above code as index.php and place it in the root directory of your web server. You can then visit http://localhost/ to see the output.
For example, visiting http://localhost/user/getAll will show the following results:
ID: 1, Name: Alice
ID: 2, Name: Bob
ID: 3, Name: Charlie
This article explains how to build a simple custom framework in PHP. A fully-fledged framework typically includes a router, controller, model, view, and core classes to handle requests and generate responses.
Custom frameworks help developers better meet project requirements and increase development efficiency. We hope this article has helped you understand how to build your own PHP framework.