PHP code example of ginger-tek / routy

1. Go to this page and download the library: Download ginger-tek/routy 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/ */

    

ginger-tek / routy example snippets




use GingerTek\Routy;

$app = new Routy;

$app = new Routy;

// Standard Function
$app->get('/', function (Routy $app) {
  $app->sendData('Hello!');
});

// Arrow Function
$app->get('/', fn () => $app->sendData('Hello!'););

// Closure
$handler = function (Routy $app) {
  $app->sendData('Hello!');
};
$app->get('/closure', $handler);

// Static Class Method
class ProductsController {
  public static function list(Routy $app) {
    ...
    $app->sendJson($products);
  }
}

$app->get('/products', \ProductsController::list(...));

$app = new Routy([
  'root' => '../',
  // i.e. app instance is created in public/index.php and your app root is one directory above

  'render' => function () {},
  // this will be called by the render method and the returned string value will be sent as the response

  'base' => '/api',
  // i.e. your app files are in /wwwroot/my-api-app and is accessed via https://domain.com/api
])

new \PDO('sqlite:' . $app->getConfig('root') . '/app.db');

$app->get('/products', ...); // HTTP GET
$app->post('/products/:id', ...); // HTTP POST
$app->put('/products', ...); // HTTP PUT
$app->patch('/products/:id', ...); // HTTP PATCH
$app->delete('/products/:id', ...); // HTTP DELETE
$app->any('/products/:id', ...); // HTTP GET, POST, PUT, PATCH, DELETE, HEAD, or OPTIONS

$app->get('*', ...); // HTTP GET for all routes
$app->any('*', ...); // Any standard HTTP method for all routes

$app->route('GET|POST', '/form', ...); // HTTP GET and POST for the /form route
$app->route('GET|POST|PUT', '/products', ...); // HTTP GET, POST and PUT for the /products route

$app->get('/products/:id', function(Routy $app) {
  $id = $app->getParam('id');
  // ...
});

function authenticate(Routy $app) {
  if(!($token = @$app->getHeaders()['authorization']))
    $app->end(401);
  $app->setCtx('user', parseToken($token));
}

$app->use(authenticate(...));

$app->get('/products', authenticate(...), function (Routy $app) {
  $userId = $app->getCtx('user')->id;
  $items = getProductsByUser($userId);
  $app->sendJson($items);
});

$app->setCtx('db', new PDO('sqlite:myData.db'));
...
$app->get('/products', function (Routy $app) {
  $db = $app->getCtx('db');
  $stmt = $db->prepare('select * from products');
  $stmt->execute();
  $result = $stmt->fetch();
  ...
})

$app = new Routy;

$app->group('/products', function (Routy $app) {
  $app->post('/', ...);
  $app->get('/', ...);
  $app->get('/:id', ...);
  $app->put('/:id', ...);
  $app->delete('/:id', ...);
});

$app->group('/products', authenticate(...), function (Routy $app) {
  $app->get('/', ...);
});

$app = new Routy;                        

$app->group('/products', function (Routy $app) {
  $app->get('/', fn (Routy $app) => $app->sendJson([]));

  // GET /products/asdf will end up here
  $app->fallback(fn () => $app->render('product-not-found'));
});

// GET /asdf will end up here
$app->fallback(fn () => $app->render('not-found'));

$app = new Routy;

$app->group('/api', ApiController::index(...));
$app->serveStatic('/nm', 'node_modules');
$app->serveStatic('/', 'public');

$app->uri;     // /some/route
$app->method;  // GET, POST, PUT, etc.

$name = $app->getQuery('name'); // <= /some/route?name=John%20Doe
echo $name; // John Doe

$param = $app->getParam('param'); // <= /some/route/:param (i.e., bob)
echo $param; // bob

$app->get('/products', function (Routy $app) {
  $body = $app->getBody();
  $body->someProperty;  // JSON: { "someProperty": "..." }
                        // or
  $body->username;      // multipart/form-data: <input name="username">
});

$app->get('/products', function (Routy $app) {
  $authToken = $app->getHeader('authorization'); // 'Bearer eyhdgs9d8fg9s7d87f...'
});

$app->post('/upload', function (Routy $app) {
  $files = $app->getFiles('field-name');
  // Destructure assignment for a single file upload
  [$file] = $app->getFiles('field-name');
});

$app->sendData('<h1>Raw HTML</h1>');

$app->sendData('path/to/file.html');

$app->sendData($base64EncodedImage, 'image/png');
$app->sendData($pathToFileWithNoExtension, 'text/csv');

$app->sendJson(['prop' => 'value']); // { "prop": "value" }
$app->sendJson([1, 2, ['three' => 4], 5]); // [1, 2, { "three: 4 }, 5]

function myRenderCallback(string $view, array $context, Routy $app): string

$app = new Routy([
  'render' => function (string $view, array $context, Routy $app): string {
    $loader = new \Twig\Loader\FilesystemLoader($app->getConfig('root') . 'views/');
    $twig = new \Twig\Environment($loader);
    $model['app'] = $app;
    return $twig->render("$view.html.twig", $model);
  }
]);
...
$app->render('home'); // views/home.html.twig
$app->render('about'); // views/about.html.twig

$app = new Routy([
  'render' => function (string $view, array $context, Routy $app): string {
    ob_start();
    $context['view'] = $app->getConfig('root') . "views/$view.php";
    extract($context, EXTR_OVERWRITE);
    

$app->post('/products', function (Routy $app) {
  $app->status(400)->sendJson(['error' => 'Bad payload']);
  // or
  $app->status(201)->sendData('<p>Successfully created!</p>');
});

$app->redirect('/go/here'); // HTTP 302
$app->redirect('/new/permanent/location', true); // HTTP 301

$app->end(); // Defaults to 200 = Success/OK
$app->end(401); // Unauthorized
$app->end(403); // Forbidden
$app->end(404); // Not Found