PHP code example of mrldavies / wp-rest-fluent

1. Go to this page and download the library: Download mrldavies/wp-rest-fluent library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mrldavies / wp-rest-fluent example snippets


use Mrldavies\WpRestFluent\Rest;

Rest::get('/hello/{name:alpha}')
    ->handler(function ($request) {
        return [
            'data' => ['message' => "Hello {$request['name']}"],
            'status' => 200,
        ];
    })
    ->formatter();

add_action('plugins_loaded', function () {
    Rest::registerRoutes();
});



namespace App\Providers;

use Roots\Acorn\Sage\SageServiceProvider;
use Mrldavies\WpRestFluent\Rest;

class ThemeServiceProvider extends SageServiceProvider
{
    public function register()
    {
        Rest::registerRoutes();
        parent::register();
    }

    public function boot()
    {
        parent::boot();
    }
}

Rest::get('/endpoint')
Rest::post('/endpoint')
Rest::put('/endpoint')
Rest::patch('/endpoint')
Rest::delete('/endpoint')

Rest::get('/product/{id:int}')
Rest::get('/user/{name:alpha}')
Rest::get('/optional/{slug?}')

Rest::get('/invoice/{ref}')

Rest::get('/category/{slug?}')

Rest::get('/legacy/age(?:/(?P<id>[0-9]+))')

return [
    'data' => $payload,
    'status' => 200,
];

return (object)[
    'data' => $payload,
    'status' => 200,
];

->formatter();

return [
  'payload' => [...],
  'code' => 418
];

Rest::get('/example')
    ->map('payload', 'code')
    ->handler(fn() => externalCall())
    ->formatter();

use Mrldavies\WpRestFluent\Middleware\RateLimitMiddleware;

Rest::get('/limited')
    ->middleware([new RateLimitMiddleware(3, 1)])
    ->handler(fn() => ['data' => ['ok' => true], 'status' => 200])
    ->formatter();

public function handle($request, $next)

return $next($request);

Rest::get('/limited')
    ->middleware([new RateLimitMiddleware(5, 1)]) // 5 requests per 1 minute
    ->handler(...)
    ->formatter();

Rest::group(['prefix' => 'v2'], function () {

    Rest::get('/users')
        ->handler(fn() => ['data' => [], 'status' => 200])
        ->formatter();

});

Rest::group([
    'prefix' => 'admin',
    'middleware' => [new RateLimitMiddleware(10, 1)],
], function () {

    Rest::get('/dashboard')
        ->permissions(fn() => current_user_can('manage_options'))
        ->handler(...)
        ->formatter();

});

Rest::get('/admin')
    ->permissions(function () {
        return current_user_can('manage_options');
    })
    ->handler(fn() => ['data' => ['ok' => true], 'status' => 200])
    ->formatter();

Rest::get('/custom')
    ->prefix('v9')
    ->handler(...)

Rest::debugRoutes();