In PhpSlides framework, routing helps in connecting HTTP requests to specific controller methods, enabling dynamic and organized request handling. This documentation demonstrates creating routes, utilizing controllers, and handling requests.
Controllers are the backbone of handling logic for specific requests. To create a controller, follow these steps:
Run the following command to generate a controller automatically:
phpslides make:controller UserController
Create a file manually in the app/Http/Controller/
directory. Make sure the file and class names end with Controller
. For example:
- File:
UserController.php
- Class:
UserController
A typical controller looks like this:
<?php
namespace App\Http\Controller;
use PhpSlides\Core\Http\Request;
final class UserController {
public function index(Request $req) {
return "Hello User";
}
}
?>
Routes link specific HTTP methods and URLs to controller methods. You can define routes as follows:
Use the namespace directly:
Route::get("add-item", [\App\Http\Controller\UserController::class, "index"]);
Alternatively, add the namespace at the top of the file:
<?php
use App\Http\Controller\UserController;
Route::get("add-item", [UserController::class, "index"]);
?>
By convention, specific methods in a controller correspond to standard HTTP requests:
-
index()
- Used for handling
GET
requests without URL parameters. - Example: Fetching a list of items.
- Used for handling
-
show()
- Handles
GET
requests with one or more URL parameters. - Example: Viewing a specific item by ID.
- Handles
-
destroy()
- Handles
DELETE
requests with one or more URL parameters. - Example: Deleting a specific resource.
- Handles
-
store()
- Handles
POST
requests. - Example: Creating a new resource.
- Handles
-
update()
- Handles
PUT
requests. - Example: Updating an existing resource.
- Handles
-
patch()
- Handles
PATCH
requests. - Example: Partially updating a resource.
- Handles
By combining routing and controllers, handling requests becomes structured and scalable. The predefined methods (index, show, etc.) ensure uniformity across routes, simplifying development. Use these principles to enhance your application's functionality and maintainability.