PHP Classes

How to Use a PHP Simple Router Class to Forward HTTP Requests to Controller Classes Using the Package Fast Router: Route request to controller set in router classes

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-09-10 (Yesterday) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
fastrouter 1.0MIT/X Consortium ...5HTTP, PHP 5, Web services, Design Pat...
Description 

Author

This package can route HTTP requests to controller classes defined in router classes.

It provides a router class that can take an array with a list of routes supported by the Web application.

The class checks the current HTTP request method and URI to find a matching route.

If it finds a route that matches the current HTTP request method and URI, the router class calls the respective controller to generate the HTTP response. Otherwise, it generates an HTTP status 404 response.

Picture of Rodrigo Faustino
  Performance   Level  
Name: Rodrigo Faustino <contact>
Classes: 24 packages by
Country: Brazil Brazil
Innovation award
Innovation award
Nominee: 16x

Winner: 2x

Example

<?php
namespace Backend\Api;
use
Backend\Api\Rotas\Router;
use
Backend\Api\Http\HttpHeader;
use
Backend\Api\Rotas\Rotas;

require_once
'../vendor/autoload.php';

HttpHeader::setDefaultHeaders();

if (
$_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
   
http_response_code(204);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];

$arrayRotas = Rotas::fastRotas();

Router::resolve($arrayRotas, $method, $uri);


Details

FastRoute - Projeto Backend

O FastRoute é um projeto de backend que visa facilitar a inclusão de rotas em uma aplicação REST, permitindo a criação rápida de endpoints CRUD com operações básicas. O banco de dados utilizado é o SQLite para facilitar os testes e a configuração inicial. Este projeto não possui frontend, focando apenas no backend.

Requisitos

  • PHP 7.4+ ou superior
  • Composer
  • Banco de dados SQLite
  • Postman ou Thunder Client (ou qualquer cliente de API REST) ## Estrutura do Projeto A estrutura de pastas do projeto está organizada da seguinte forma:
/backend
    /Controllers
        - UserController.php
    /Database
        - config.php
        - Database.php
    /Http
        - HttpHeader.php
    /Models
        - User.php
    /Repositories
        - UserRepository.php
    /Rotas
        - rotas.php
        - Router.php
    - agenda.db
    - index.php
/vendor
.gitignore
composer.json

Configuração

Clone o repositório:

git clone https://github.com/faustinopsy/FastRoute.git

Baixe as dependencias do composer

composer install

Navegue até a pasta backend:

cd backend

Inicialize o servidor PHP:

Inicie o servidor embutido do PHP dentro da pasta backend para facilitar o teste:

php -S localhost:8000

Endpoints Disponíveis

O projeto inclui cinco operações CRUD nas mesmas rotas, variando apenas o método HTTP. Veja abaixo os endpoints disponíveis:

  • GET /users - Retorna todos os usuários
  • GET /users/{id} - Retorna um usuário específico pelo ID
  • POST /users - Cria um novo usuário
  • PUT /users/{id} - Atualiza um usuário existente pelo ID
  • DELETE /users/{id} - Deleta um usuário existente pelo ID

Exemplo de Requisição com JSON

Para testar os endpoints, você pode usar o Postman ou Thunder Client.

Exemplo para criar um novo usuário (POST /users):

Método: POST

URL: http://localhost:8000/users Body (raw JSON):

{
  "nome": "seunomex",
  "email": "seunomex@gmail.com",
  "senha": "1234"
}

Exemplo de Atualização de Usuário

Método: PUT URL: http://localhost:8000/users/1 Body (raw JSON):

{
  "nome": "nomeatualizado",
  "email": "emailatualizado@gmail.com",
  "senha": "nova_senha"
}

Exemplo de Deleção de Usuário

Método: DELETE URL: http://localhost:8000/users/1


  Files folder image Files (11)  
File Role Description
Files folder imagebackend (1 file, 6 directories)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file readme.md Doc. Documentation

  Files folder image Files (11)  /  backend  
File Role Description
Files folder imageControllers (1 file)
Files folder imageDatabase (2 files)
Files folder imageHttp (1 file)
Files folder imageModels (1 file)
Files folder imageRepositories (1 file)
Files folder imageRotas (2 files)
  Accessible without login Plain text file index.php Example Example script

  Files folder image Files (11)  /  backend  /  Controllers  
File Role Description
  Plain text file UserController.php Class Class source

  Files folder image Files (11)  /  backend  /  Database  
File Role Description
  Accessible without login Plain text file config.php Aux. Configuration script
  Plain text file Database.php Class Class source

  Files folder image Files (11)  /  backend  /  Http  
File Role Description
  Plain text file HttpHeader.php Class Class source

  Files folder image Files (11)  /  backend  /  Models  
File Role Description
  Plain text file User.php Class Class source

  Files folder image Files (11)  /  backend  /  Repositories  
File Role Description
  Plain text file UserRepository.php Class Class source

  Files folder image Files (11)  /  backend  /  Rotas  
File Role Description
  Plain text file rotas.php Class Class source
  Plain text file Router.php Class Class source

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 100%
Total:0
This week:0