Skip to content

Instantly share code, notes, and snippets.

@tonyhb
Created June 20, 2010 14:07
Show Gist options
  • Save tonyhb/445868 to your computer and use it in GitHub Desktop.
Save tonyhb/445868 to your computer and use it in GitHub Desktop.
/**
* Set the routes. Each route must have a minimum of a name, a URI and a set of
* defaults for the URI.
*/
Route::set('api', '(<action>(/<id>))')
->defaults(array(
'subdomain' => 'api',
'controller' => 'api',
'action' => 'subdomain',
));
Route::set('default', '(<controller>(/<action>(/<id>)))')
->defaults(array(
'controller' => 'welcome',
'action' => 'index',
));
/**
* Execute the main request. A source of the URI can be passed, eg: $_SERVER['PATH_INFO'].
* If no source is specified, the URI will be automatically detected.
*/
try
{
$request = Request::instance();
// execute (returns response) & send headers
$response = $request->execute();
// echo content
echo $response->send_headers()->body();
}
catch( exception $e )
{
if(Kohana::$environment === Kohana::DEVELOPMENT)
{
// re-throw error
throw($e);
}
else
{
// log it
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// get type of error
switch(get_class($e))
{
// no controller/action for this uri
case 'ReflectionException':
// no route for the uri
case 'Kohana_Request_Exception':
// throw a 404
$response = new Response();
$response->status = 404;
$response->body = /* View::factory('errors/404')->render(); */ '404';
echo $response->send_headers()->body();
break;
}
}
}
<?php defined("SYSPATH") or die();
class controller_api extends controller {
public function before()
{
if($this->request->subdomain != 'api')
throw new Kohana_Request_Exception('404 Not Found', null, 404);
}
public function action_subdir()
{
$this->response->body = "This is a <strong>subdirectory</strong> API call";
}
public function action_subdomain()
{
$this->response->body = "This is a <strong>subdomain</strong> API call";
}
public function action_hmvc()
{
// Create a new HMVC request. Set the subdomain to false to access default route.
$this->response->body = Request::factory('/welcome/index', array('subdomain' => false))->execute();
}
public function after()
{
$this->response->body .= '<h6>Request: </h6>';
$this->response->body .= Kohana::debug($this->request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment