Pexpress is a lightweight PHP library for building RESTful APIs with ease. It provides a simple and intuitive interface for defining routes and handling HTTP requests. This README will guide you through the process of installing and using the Pexpress library effectively.
- Installation
- Usage
- Initializing the App
- Defining Routes
- Listening to Requests
- Examples
- Contributing
- License
To use Pexpress in your PHP project, you need to follow these steps:
- Update your
composer.json
file to include the library as a dependency:
"require": {
"henacodes/pexpress": "dev-master"
}
-
Run the following command to install the library and its dependencies:
composer install
To get started with Pexpress, you need to initialize the App class. This class will be responsible for handling incoming requests and routing them to the appropriate handlers.
In your PHP file (index.php or any other file), include the autoload file generated by Composer:
require_once 'vendor/autoload.php';
Next, import the App namespace:
use Henacodes\Pexpress\App;
Now, you can initialize the App class:
$app = new App();
Pexpress allows you to define routes using different HTTP methods such as GET, POST, PUT, and PATCH. To define a route, you need to call the corresponding method on the $app instance and provide a callback function that will handle the request.
Here's an example of defining a GET route:
$app->get("/users/:id", function ($req, $res, $next) {
$res->json(["message" => "Hello"]);
});
You can define routes for other HTTP methods in a similar manner (post, put, patch).
After defining your routes, you need to start listening for incoming requests. To do this, simply call the listen method on the $app instance:
$app->listen();
This will start the server and listen for incoming requests on the specified port (usually port 8000).
You can add as many middlewares as possible. Here is an example
$middleware_one = function($request, $response, $next){
if (your_logic_here){
// if its true , preceed to the next miiddleware
$next()
} else {
// abort the process and response with an error response
res.status(400)
res.json({ error:"Bad request" })
}
}
$middleware_two = function($request, $response, $next){
// your second middleware
}
$app->get("/posts", $middleware_one, $middleware_two)
For more examples and usage details, please refer to the examples directory in this repository.
Contributions are welcome! If you have any improvements or new features to add, please create a pull request.
This project is licensed under the MIT License.