Rabbit es un framework PHP ligero y modular, diseñado para ofrecer flexibilidad y escalabilidad en el desarrollo de APIs. Se encuentra en sus primeras etapas de desarrollo.
- PHP 8.x o superior
- Composer (próximamente disponible)
- Instalar Gettext en el servidor para el correcto funcionamiento de las traducciones Ver pasos
Por ahora, Rabbit solo está disponible para ser descargado directamente desde GitHub.
-
Clona el repositorio:
git clone https://github.com/mmrasteu/phprabbit-framework.git
-
Accede a la carpeta del proyecto:
cd rabbit-framework- Comienza a crear tu proyecto y ajusta el autoload según tus necesidades.
Rabbit no es instalable actualmente mediante Composer. Planeamos integrar Composer en versiones posteriores.
Las versiones betas no son recomendables para un desarrollo seguro. Están publicadas para poder ser estudiadas y para aceptar colaboraciones.
Ejemplo básico de definición de rutas:
//Se añade la ruta /auth al grupo que usa el prefijo /api
Router::group(['prefix' => '/api', 'middlewares' => []], function () {
Router::POST('/auth', ['AuthController', 'getBearerToken']);
});Puedes agregar middleware en tu aplicación para validar tokens, manejar autenticación o realizar otras tareas. Se asignan a grupos de rutas.
Si el middleware necesita parámetros para instanciarse, se deben pasar dentro de un array como se muestra en el ejemplo.
Ejemplo de uso de Middlewares:
//Se pueden definir varios grupos con el mismo prefijo. A este grupo se le añade el middleware `TestMiddleware`
Router::group(['prefix' => '/api', 'middlewares' => ['TestMiddleware']], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});//Se pueden definir varios grupos con el mismo prefijo. A este grupo se le añade el middleware `ParametizableMiddleware` con un parámetro `param1`
Router::group(['prefix' => '/api', 'middlewares' => ['ParametizableMiddleware' => ['param1']]], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});El Bearer Token generado al iniciar sesión con un usuario API tiene implícito un rol ('api_user' por defecto) para aplicar esta restricción de acceso vinculada al Bearer Token. El middleware RoleMiddleware se encargará de la gestión de permisos. A continuación se muestra un ejemplo de un endpoint sin necesidad de Bearer Token para llamarlo, un endpoint accesible solo al role 'user_admin' y otro endpoint accesible por todos los usuarios (pero que necesariamente solo se le puede llamar con autenticación con Bearer Token).
Ejemplo de uso:
- Sin autenticación
Router::group(['prefix' => '/api', 'middlewares' => []], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});- Con autenticación, habilitado solo para usuarios con rol 'api_user'
Router::group(['prefix' => '/api', 'middlewares' => ['RoleMiddleware'=>['api_user']]], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});- Con autenticación, habilitado solo para todos los usuarios.
Router::group(['prefix' => '/api', 'middlewares' => ['RoleMiddleware'=>[]]], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});Ejemplo de cómo usar las respuestas con código de estado. Estas respuestas se pueden personalizar.
. . .
// Se obtiene el valor de los parámetros. En este caso del parámetro 'id' que contiene el valor '123'
$id = $this->request->getParam('id');
//Se crea un array con los datos que se mostrarán en la respuesta
$data = [
'id' => (int) $id
];
//Se envía el $data a la clase Response
$this->response->withStatus200($data);
. . .Respuesta API:
{
"status": 200,
"title": "Success",
"message": "200 - Success",
"data": {
"id": 123
}
}Valida si el valor es una dirección de correo electrónico válida.
Valida si el valor es un número. Acepta cualquier tipo de valor numérico, incluyendo enteros y flotantes.
Valida si el valor es una fecha válida según el formato dado (por ejemplo, 'Y-m-d'). El formato por defecto se especifica en la variable de entorno DEFAULT_DATETIME_FORMAT
Valida si el valor es un valor booleano (true o false), o si es una cadena que representa un valor booleano (como "true", "false").
Valida si el valor es un array.
Valida si el valor es una URL válida.
Valida si el valor contiene solo caracteres alfabéticos (letras, sin números ni símbolos).
Valida si el valor contiene solo caracteres alfanuméricos (letras y números).
- sudo apt-get install gettext
- Descomentar "es_ES.UTF-8 UTF-8" en
/etc/locale.gensi es necesario. - sudo locale-gen
- sudo update-locale
- msgfmt ./locale/es_ES/LC_MESSAGES/messages.po -o ./locale/es_ES/LC_MESSAGES/messages.mo
Si deseas contribuir a Rabbit, por favor sigue estos pasos:
- Haz un fork del repositorio.
- Crea una nueva rama (
git checkout -b feature/nueva-caracteristica). - Realiza tus cambios y haz commit de ellos.
- Envía un pull request con una descripción clara de los cambios.
Este proyecto está bajo la Licencia MIT - consulta el archivo LICENSE para más detalles.
Puedes ponerte en contacto conmigo a través de [mmrasteu@gmail.com] para cualquier pregunta o sugerencia.
Rabbit is a lightweight and modular PHP framework designed to offer flexibility and scalability in API development. It is in its early stages of development.
- PHP 8.x or higher
- Composer (coming soon)
- Install Gettext on the server for proper translation functionality See steps
For now, Rabbit is only available for direct download from GitHub.
- Clone the repository:
git clone https://github.com/mmrasteu/phprabbit-framework.git- Navigate to the project folder:
cd rabbit-framework- Start creating your project and adjust the autoload as needed.
Rabbit is currently not installable via Composer. We plan to integrate Composer in future versions.
Beta versions are not recommended for safe development. They are released for study purposes and to accept contributions.
Basic example of route definition:
// Adds the /auth route to the group using the /api prefix
Router::group(['prefix' => '/api', 'middlewares' => []], function () {
Router::POST('/auth', ['AuthController', 'getBearerToken']);
});You can add middleware to your application to validate tokens, handle authentication, or perform other tasks. Middleware is assigned to route groups.
If the middleware requires parameters for instantiation, they should be passed in an array as shown in the example.
Example of using Middlewares:
// Multiple groups with the same prefix can be defined. This group adds the `TestMiddleware`
Router::group(['prefix' => '/api', 'middlewares' => ['TestMiddleware']], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});// Multiple groups with the same prefix can be defined. This group adds the `ParametizableMiddleware` with a parameter `param1`
Router::group(['prefix' => '/api', 'middlewares' => ['ParametizableMiddleware' => ['param1']]], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});The Bearer Token generated when logging in with an API user has an implied role ('api_user' by default) to apply this access restriction linked to the Bearer Token. The RoleMiddleware handles permission management. Below is an example of an endpoint that does not require a Bearer Token to call, an endpoint accessible only to the 'user_admin' role, and another endpoint accessible to all users (but must be called with Bearer Token authentication).
Example of usage:
- Without authentication
Router::group(['prefix' => '/api', 'middlewares' => []], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});- With authentication, enabled only for users with 'api_user' role
Router::group(['prefix' => '/api', 'middlewares' => ['RoleMiddleware'=>['api_user']]], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});- With authentication, enabled for all users
Router::group(['prefix' => '/api', 'middlewares' => ['RoleMiddleware'=>[]]], function () {
Router::GET('/test', ['StatusController', 'getStatus']);
});Example of how to use responses with status codes. These responses can be customized.
. . .
// Retrieves the value of the parameters. In this case, from the 'id' parameter which contains the value '123'
$id = $this->request->getParam('id');
// Creates an array with the data that will be shown in the response
$data = [
'id' => (int) $id
];
// Sends the $data to the Response class
$this->response->withStatus200($data);
. . .API Response:
{
"status": 200,
"title": "Success",
"message": "200 - Success",
"data": {
"id": 123
}
}Validates if the value is a valid email address.
Validates if the value is a number. Accepts any type of numeric value, including integers and floats.
Validates if the value is a valid date according to the given format (e.g., 'Y-m-d'). The default format is specified in the environment variable DEFAULT_DATETIME_FORMAT
Validates if the value is a boolean (true or false), or if it's a string that represents a boolean value (such as "true", "false").
Validates if the value is an array.
Validates if the value is a valid URL.
Validates if the value contains only alphabetic characters (letters, no numbers or symbols).
Validates if the value contains only alphanumeric characters (letters and numbers).
- sudo apt-get install gettext
- sudo locale-gen
- sudo update-locale
- msgfmt ./locale/es_ES/LC_MESSAGES/messages.po -o ./locale/es_ES/LC_MESSAGES/messages.mo
If you would like to contribute to Rabbit, please follow these steps:
- Fork the repository.
- Create a new branch (
git checkout -b feature/new-feature). - Make your changes and commit them.
- Send a pull request with a clear description of the changes.
This project is licensed under the MIT License - see the LICENSE file for details.
You can contact me via [mmrasteu@gmail.com] for any questions or suggestions.