public function __construct(\Slim\Slim $slim) { $this['slim'] = $slim; $router = new Router($slim); $router->register('index', new Controllers\Index($this)); $router->register('csv', new Controllers\Csv($this)); $router->register('csv/upload', new Controllers\Csv($this)); $router->defaultRoute('index'); }
public static function routes() { static::loadModules(); foreach (static::$modulesObjects as $object) { $object->routes(); } //Load login routes.. login, logoff, etc.. Router::register("GET", "manager/api/config/", function () { header("Content-Type: text/javascript; charset=utf-8"); if (Request::isLocal()) { if (@DB::query("select id from " . J_TP . "manager_users LIMIT 1;")->success === false) { DB::query("CREATE TABLE `" . J_TP . "manager_users` (\n\t\t\t\t\t\t\t\t`id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\t\t\t\t\t\t`name` varchar(255) DEFAULT NULL,\n\t\t\t\t\t\t\t\t`email` varchar(255) DEFAULT NULL,\n\t\t\t\t\t\t\t\t`typeID` int(11) unsigned NULL,\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t`username` varchar(255) DEFAULT NULL,\n\t\t\t\t\t\t\t\t`password` varchar(40) DEFAULT NULL,\n\t\t\t\t\t\t\t\t`active` int(11) DEFAULT NULL,\n\t\t\t\t\t\t\t\tPRIMARY KEY (`id`)\n\t\t\t\t\t\t\t) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;"); $user = ORM::make("manager_users"); $user->name = "Joy Interactive"; $user->email = "*****@*****.**"; $user->username = "******"; $user->password = "******"; $user->typeID = 1; $user->active = 1; $user->save(); } if (@DB::query("select id from " . J_TP . "manager_tokens LIMIT 1;")->success === false) { DB::query("CREATE TABLE `" . J_TP . "manager_tokens` (\n\t\t\t\t\t\t\t\t`id` int(40) NOT NULL AUTO_INCREMENT,\n\t\t\t\t\t\t\t\t`userID` int(11) DEFAULT NULL,\n\t\t\t\t\t\t\t\t`typeID` int(11) DEFAULT NULL,\n\t\t\t\t\t\t\t\t`token` varchar(100) DEFAULT NULL,\n\t\t\t\t\t\t\t\t`expirationDate` datetime DEFAULT NULL,\n\t\t\t\t\t\t\t\tPRIMARY KEY (`id`)\n\t\t\t\t\t\t\t) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;"); } } $config = array(); $config["api_url"] = URL::to("api/"); return "window.config = " . json_encode($config); }); Router::register("GET", "manager/api/structure/", function () { return Response::json(Structure::modules()); }); Router::register("POST", "manager/api/token/", function () { return User::generateToken(); }); Router::register("POST", "manager/api/token/renew/", function () { return User::renewToken(); }); Router::register("GET", "manager/api/logout/", function () { return User::logout(); }); Router::register("GET", "manager/api/customJS/", function () { $path = J_MANAGERPATH . "custom.js"; if (file_exists($path)) { return File::get($path); } }); }
public static function restful($uri, $name) { $methods = array("restIndex#GET#/", "restGet#GET#/(:num)", "restNew#GET#/new", "restCreate#POST#/", "restUpdate#PUT#/(:num)", "restDelete#DELETE#/(:num)"); $uri = trim($uri, "/"); $pieces = explode(DS, $name); $className = $pieces[count($pieces) - 1] = ucfirst(array_last($pieces)) . "Controller"; $path = J_APPPATH . "controllers" . DS . trim(implode(DS, $pieces), DS) . EXT; if (Request::isLocal()) { if (!File::exists($path)) { trigger_error("File <b>" . $path . "</b> doesn't exists"); } } require $path; $instance = new $className(); foreach ($methods as $method) { $method = explode("#", $method); if (method_exists($instance, $method[0])) { Router::register($method[1], $uri . $method[2], $name . "@" . $method[0]); } } }
function register($methods = null) { \Router::register($methods ?: $this->methods, $this->url, $this->toArray()); return $this; }
public static function reg($route, $action, $method = null) { $_method = is_null($method) ? 'ANY' : $method; Router::register($_method, $route, $action); }
$router->register('thumbs(\\/.*)?/(:any)-([1-9][0-9]{2,3})-([a-f0-9]{12})(\\.(jpeg|jpg|png)$)', array('method' => 'GET', 'action' => function ($path, $filename, $width, $hash, $extension) { // check if the requested width is within the defined range if ($width % 100 !== 0 || $width > 3000) { header::notfound(); exit; } // page or site kirby()->site()->visit(); if (strlen($path) !== 0) { $page = kirby()->site()->find($path); } else { $page = kirby()->site(); } if ($page && ($image = $page->file($filename . $extension))) { $modified = substr(md5($image->modified()), 0, 12); if ($modified === $hash) { // thumb root $path = str_replace('/', DS, $page->id()); $root = kirby()->roots()->index() . DS . 'thumbs' . DS . $path; // create directories if necessary if (!f::exists($root)) { dir::make($root, true); } // thumb url $url = kirby()->urls()->index() . '/thumbs/' . $page->id(); // create thumb $thumb = thumb($image, array('destination' => true, 'width' => $width, 'filename' => '{safeName}-{width}-' . $modified . '.{extension}', 'root' => $root, 'url' => $url)); // send headers header::type($image->mime()); header('Cache-control: max-age=' . 60 * 60 * 24 * 365); header('Expires: ' . gmdate(DATE_RFC1123, time() + 60 * 60 * 24 * 365)); // read file function readFileChunked($filename, $retbytes = true) { $chunkSize = 8192; $buffer = ''; $cnt = 0; $handle = fopen($filename, 'rb'); if ($handle === false) { return false; } while (!feof($handle)) { $buffer = fread($handle, $chunkSize); echo $buffer; ob_flush(); flush(); if ($retbytes) { $cnt += strlen($buffer); } } $status = fclose($handle); if ($retbytes && $status) { return $cnt; } return $status; } readFileChunked($thumb->root()); } else { header::notfound(); exit; } } else { header::notfound(); exit; } }));
<?php /* Ex: Router::register("GET", "/", "index"); //view Router::register("GET", "/", "index@method"); //controller -> IndexController::method() Router::register("GET", "/", function () { }); //callback Router::register("GET", "/detail/(:num)", function ($id) { return $id; }); //with params */ Router::register("GET", "/", "index"); Router::register("GET", "/modal_data", function () { return Response::json(array('title' => 'Titulo :)')); });
<?php /* * * This is an example controller * Controller can also be a class with methods as templates controllers */ include_once 'router.php'; $router = new Router(); $router->register('GET', '/', 'home'); function home() { echo 'Hello, World.'; } $router->register(array('GET', 'POST'), 'users/(?P<id>\\d+)/', 'get_user_id'); function get_user_id($id) { echo "Get user {$id}"; } $router->register('GET', 'users/(?P<id>\\d+)/(?P<name>\\w+)/', 'get_user'); function get_user($id, $name) { echo "Get user {$id}, {$name}"; } $router->dispatch();
| | It's easy to allow URI wildcards using (:num) or (:any): | | Route::put('hello/(:any)', function($name) | { | return "Welcome, $name."; | }); | */ Route::get('(:any)', 'stats@index'); Route::post('postanswers/(:any)', 'postanswers@index'); Route::post('multichoice/(:any)/postanswers', 'multichoice@postAnswers'); Router::register(array('GET', 'POST'), 'multichoice/(:any)/getquestions', 'multichoice@getQuestions'); Route::get('multichoice/(:any)/(:num?)', 'multichoice@index'); Route::get('matching/(:any)/(:num?)', 'matching@index'); Router::register(array('GET', 'POST'), 'matching/(:any)/getquestions', 'matching@getQuestions'); Route::get('/', 'picker@index'); /* |-------------------------------------------------------------------------- | Application 404 & 500 Error Handlers |-------------------------------------------------------------------------- | | To centralize and simplify 404 handling, Laravel uses an awesome event | system to retrieve the response. Feel free to modify this function to | your tastes and the needs of your application. | | Similarly, we use an event to handle the display of 500 level errors | within the application. These errors are fired when there is an | uncaught exception thrown in the application. | */
public function __construct($name, $label, $path) { parent::__construct($name, $label); $this->type = "upload"; $id = uniqueID(); $this->sessionKey = "manager_" . $this->type . $id; $this->updateURL = "fields/" . $this->type . $id; $this->limit = 1; $this->hasCaption = false; $this->path = $path; $this->defaultValue = array(); $this->accepts = array(); $this->acceptsMask = null; $that = $this; Router::register("POST", "manager/api/" . $this->updateURL . "/(:segment)/(:num)/(:segment)", function ($action, $id, $flag) use($that) { if (($token = User::validateToken()) !== true) { return $token; } $flag = Str::upper($flag); $that->module->flag = $flag; switch ($action) { default: case "update": return Response::json($that->upload($flag, $id)); break; case "sort": return Response::json($that->sort(Request::post("from", -1), Request::post("to", -1))); break; case "caption": return Response::json($that->setCaption((int) Request::post("index", -1), Request::post("caption"))); break; case "delete": return Response::json($that->delete((int) Request::post("index", -1))); break; } return Response::code(500); }); }
$allowed = true; break; } } if (!$allowed || count($pieces) == 0) { return Response::code(403); } $path = implode(DS, $pieces); if (!File::exists(J_PATH . $path) || is_dir(J_PATH . $path)) { return Response::code(404); } $im = new Image(J_PATH . $path); $im->resize((int) Request::get("width"), (int) Request::get("height"), Request::get("method", "fit"), Request::get("background", 0xffffff)); $im->header(); }); Router::register("*", "(:all)", function () { Response::code(404); if (Request::isLocal()) { echo "URI: " . URI::full() . "<br>\n"; echo "Path Info: " . Request::pathInfo() . "\n"; } return; }); if (URI::isManager()) { Structure::routes(); } Request::$route = Router::route(Request::method(), URI::current()); Event::fire(J_EVENT_RESPONSE_START); echo Request::$route->call(); Event::fire(J_EVENT_RESPONSE_END); //echo "<br><br>" . round(elapsed_time() * 1000000) / 1000 . "ms";
$F->loadResource("resources/*", "utils/ErrorHandler/index.php"); /******************************************************/ View::$root = dirname(__FILE__); View::$forEachView = array("globalVar" => "global variable"); class CheckSession { public function __construct($params) { var_dump("Controller CheckSession run"); } } class ControllerHome { public function __construct($params) { die(view("/tpl/home.html", array("titleOfThePage" => "Fabrico test", "title" => "Fabrico", "content" => "It works!"))); } } class ControllerUsers { public function __construct($params) { $userId = isset($params["id"]) ? $params["id"] : "none (please add something after /users/)"; die(view("/tpl/users.html", array("titleOfThePage" => "Fabrico test", "title" => "Users", "content" => "The user id is: " . $userId))); } } // test instance of custom resource $config = new MyCustomConfig(); $router = new Router(); $router->register("/users/@id", array("CheckSession", "ControllerUsers"))->register("/users", "ControllerUsers")->register("", "ControllerHome")->run();
}); Router::register('S3/resume', function () { S3Controller::resume(); }); Router::register('stats', function () { GLOBALvarGet('CJob')->requireLogin(); GLOBALvarGet('CStats')->loadStats(); }); Router::register('team', function () { GLOBALvarGet('CApp')->team(); }); Router::register('terms', function () { GLOBALvarGet('CApp')->terms(); }); Router::register('whereto', function () { GLOBALvarGet('CStudent')->whereto(); }); // Map route to registered functions. Try to have these in alphabetical order, // and then in groupings. Router::route('/index', 'index'); Router::route('/', 'index'); Router::route('/admin/login', 'admin/login'); Router::route('/admin/questions', 'admin/questions'); Router::route('/housing', 'backtoindex'); Router::route('/housing/index', 'backtoindex'); Router::route('/jobs', 'backtoindex'); Router::route('/jobs/index', 'backtoindex'); Router::route('/hubs', 'backtoindex'); Router::route('/hubs/index', 'backtoindex'); Router::route('/changepass', 'changepass'); Router::route('/confirm', 'confirm');