Skip to content

Application

John Aldrich Bernardo edited this page Feb 14, 2018 · 5 revisions

Creating a new Calf Application

Calf Application is just a wrapper for everything in Calf. The only difference is just it gives the Saddle (Dependency Container) to the route you have provided.

<?php

require_once('vendor/autoload.php');

// Create a new Saddle (Dependency Injector)
$container = new \Calf\Saddle();

// More examples for our Saddle
$container->products = [
    'supplies'  => ['Pen'],
    'fruits'    => ['Apple', 'Pineapple']
];

$container->getProducts = function(\Calf\Saddle $c) {
    return $c->products;
};
// Let's instantiate our application
$app = new \Calf\App($container);

Functions

add :void

Add a new route to the application.

Parameters:

  • $route: \Calf\HTTP\Route - Route to be added.
// Our homepage
$home = new \Calf\HTTP\Route('/', function(\Calf\HTTP\Request $req, \Calf\HTTP\Response $res, array $args = []) {
    // $this->message is the data from our container
    $res->write($this->message);
    // Return response
    return $res;
}, ['GET', 'POST']);

$app->add($home);

addGroup :void

Add route group.

Parameters:

  • $group: \Calf\HTTP\RouteGroup - Route group to be added.
// Products Service Route Group
$products = new \Calf\HTTP\RouteGroup('products');
$products->add(
    // Test using url:
    // {host}/products/get
    new \Calf\HTTP\Route('/get', function(\Calf\HTTP\Request $req, \Calf\HTTP\Response $res, array $args = []) {
        $res->write($this->getProducts);
        return $res;
    }, 'GET')
);
$products->add(
    // Test using url:
    // {host}/products/get/{fruits|supplies|...}
    new \Calf\HTTP\Route('/get/{category:\w+}', function(\Calf\HTTP\Request $req, \Calf\HTTP\Response $res, array $args = []) {
        $prods = [];
        $category = $args['category'];
        if (!isset($this->getProducts[$category])) {
            $res->write('No products found for keyword: ' .$category);
            return $res;
        }
        
        $prods = $this->getProducts[$category];
        $res->write('Available: ');
        $res->write(implode(', ', $prods));
        return $res;
    }, 'GET')
);

// Register route group to application
$app->addGroup($products);

getContainer :\Calf\Saddle

Returns the Calf Saddle (Dependency Container) that the application is using.

getRouter :\Calf\HTTP\Router

Returns the Calf Router instantiated by the application.

run: \Calf\HTTP\Response

Run the Calf Application.

Parameters:

  • $silent: boolean (false) - Do not render response
$response = $app->run(true);

Middlewares

Calf Application also allows application-level middlewares.

$app->addMiddleware(function(\Calf\HTTP\Request $req, \Calf\HTTP\Response $res, callable $next) {
    $res->write('[BEGIN]');
    $next($req, $res);
    $res->write('[END]');
    return $res;
});

Clone this wiki locally