-
Notifications
You must be signed in to change notification settings - Fork 0
Application
John Aldrich Bernardo edited this page Feb 14, 2018
·
5 revisions
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);Add a new route to the application.
-
$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);Add route group.
-
$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);Returns the Calf Saddle (Dependency Container) that the application is using.
Returns the Calf Router instantiated by the application.
Run the Calf Application.
-
$silent:boolean(false)- Do not render response
$response = $app->run(true);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;
});The calf is open-sourced software licensed under the MIT license.