riverside/php-express

PHP micro-framework inspired by Express.js

2.0.0 2024-09-14 17:45 UTC

This package is auto-updated.

Last update: 2024-11-23 10:48:26 UTC


README

PHP micro-framework inspired by Express.js

Requirements

  • PHP >= 7.1
  • PHP extensions:
    • JSON (ext-json)

Installation

If Composer is not installed on your system yet, you may go ahead and install it using this command line:

$ curl -sS https://getcomposer.org/installer | php

Next, add the following require entry to the composer.json file in the root of your project.

{
    "require" : {
        "riverside/php-express" : "^2.0"
    }
}

Finally, use Composer to install php-express and its dependencies:

$ php composer.phar install 

Routing

<?php
$app = new \Riverside\Express\Application();

$app->get('/', function ($req, $res) {
     $res->send('hello world');
});

Route methods

<?php
// GET method route
$app->get('/', function ($req, $res) {
    $res->send('GET request to the homepage');
});

// POST method route
$app->post('/', function ($req, $res) {
    $res->send('POST request to the homepage');
});

Route paths

<?php
$app->get('/', function ($req, $res) {
    $res->send('root');
});

$app->get('about', function ($req, $res) {
    $res->send('about');
});

$app->get('random.text', function ($req, $res) {
    $res->send('random.text');
});

Response methods

$app->route()

<?php
$app->route('/book')
    ->get(function ($req, $res) {
        $res->send('Get a random book');
    })
    ->post(function ($req, $res) {
        $res->send('Add a book');
    })
    ->put(function ($req, $res) {
        $res->send('Update the book');
    });

Router

<?php
$router = new \Riverside\Express\Router($app);

$router->param('uuid', '[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}');

$router->get('/', function ($req, $res) {
    $res->send('Birds home page');
});

$router->get('about', function ($req, $res) {
    $res->send('About birds');
});

$router->get('ticket/:uuid/', function($req, $res) {
    echo $req->params['uuid'];
});

$router->run();

Middleware

$app->use(function($req, $res) {
    $res->header('X-Frame-Options', 'DENY');
    $res->header('X-Powered-By', false);
});

$app->use('/cors', function($req, $res) {
    $res->header('Access-Control-Allow-Origin', '*');
});