


How to build a personal PHP framework suitable for small or personal projects
With the continuous development of Internet applications, the development of Web applications has attracted more and more attention. In the development of web applications, using frameworks can effectively speed up development and improve stability. As a popular web programming language, PHP has many mature and excellent frameworks, such as Laravel, CodeIgniter, Yii, etc. However, in the development of some small or personal projects, using these mature frameworks may appear to be too bloated or too complex. At this time, it becomes particularly important to build your own personal framework. This article will introduce how to build a personal PHP framework suitable for small or personal projects.
1. Routing
Routing is an important part of the Web framework. It is a mechanism to determine which controller should be called based on the requested URL. In a simple PHP framework, routing can be implemented using the following code:
// 解析请求的uri,比如/index.php/user/list $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // 删除前导斜杠并选择控制器及其方法 if ('/index.php' === $uri || '/' === $uri) { $controller = 'home'; $action = 'index'; } else { $uri = ltrim($uri, '/'); $uri_parts = explode('/', $uri); $controller = $uri_parts[0]; $action = $uri_parts[1]; } // 根据路由调用对应的控制器及其方法,如Home::index() $controller_name = $controller.'Controller'; $controller_file = __DIR__.'/controllers/'.$controller_name.'.php'; // 判断控制器文件是否存在 if (file_exists($controller_file)) { require_once $controller_file; $controller_instance = new $controller_name(); // 判断控制器方法是否存在 if (method_exists($controller_instance, $action)) { $controller_instance->$action(); } else { echo '404 Not Found'; } } else { echo '404 Not Found'; }
The code here implements a simple routing rule: use the first part of the URL as the controller name, and use the first part of the URL as the controller name. The second part serves as the method name that the controller needs to execute. The controller file needs to exist in the controllers directory. In the controller file, you can write classes to implement specific functions, for example:
class HomeController { public function index() { echo 'Hello, World!'; } }
The above code will output "Hello, World!". If the access URL is /index.php/home/index, the index method of the HomeController class will be called and "Hello, World!" will be output. Through this simple routing mechanism, we can implement simple URL routing functions very conveniently.
2. Request and response
In Web applications, requests and responses are two indispensable parts. Usually, the user makes a request to the Web server through the browser, the Web server receives the request, processes it, and finally returns a response. In the PHP personal framework, request parsing and response output can be achieved through the following code:
// 解析请求方式和请求参数 $request_method = strtolower($_SERVER['REQUEST_METHOD']); if ('post' === $request_method) { $request_params = $_POST; } elseif ('get' === $request_method) { $request_params = $_GET; } else { $request_params = []; } // 响应输出 function response($data, $content_type = 'application/json') { header('Content-Type: '.$content_type); echo $data; } // 将请求转换为JSON格式的响应 $response_data = json_encode($request_params); response($response_data);
The above code first determines the request method. If it is a POST request, its parameters will be parsed into the $_POST array. If If it is a GET request, its parameters will be parsed into the $_GET array. PHP's built-in strtolower() function is used here to convert the request method into lowercase letters. Then, in the response function, call the header function to set the response Content-Type, and then use echo to output $data. In this example, $data is a JSON string, and the request parameters are converted to JSON format using the json_encode() function. By encapsulating the response output into a function, it can be more conveniently used in different controllers and methods.
3. Database operation
In web applications, it is often necessary to use a database for data storage and query. In the PHP personal framework, you can use PDO to perform database operations. The following is an example of using PDO to obtain a list of all users in the database:
try { // 连接到本地数据库 $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password'); // 设置错误报告 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 查询所有用户 $stmt = $pdo->prepare('SELECT * FROM users'); $stmt->execute(); // 处理查询结果 // fetch()方法用于取回当前行并向后移动指针 // fetchAll()方法一次性将所有行取回并存储在一个数组中 $users = $stmt->fetchAll(); // 输出用户列表 response(json_encode($users)); } catch (PDOException $e) { echo 'Database Error: '.$e->getMessage(); }
In the above code, first use PDO to connect to the database, and set the error mode of PDO to ERRMODE_EXCEPTION so that PDO exceptions can be captured. Then, use the PDO::prepare() method to prepare a query statement, use the PDO::execute() method to execute the query, and use the PDOStatement::fetchAll() method to retrieve all rows in the result set. Finally, the result set is converted to JSON format and output. In actual applications, PDO operations can be encapsulated into functions or classes as needed to facilitate reuse and management.
In summary, this article introduces the basic implementation principles of the PHP personal framework, including routing, requests and responses, and database operations. Of course, this is just a simple example framework. In actual framework development, many details and technical difficulties need to be considered. In the process of developing a PHP personal framework, you need to constantly understand and learn the latest technologies and methods to make the framework more efficient and practical.
The above is the detailed content of How to build a personal PHP framework suitable for small or personal projects. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools