/** * The most important method. * Will start the hive engine and listening for requests. * * @param Request $request * @param AbstractResponse $response * @param boolean $sendResponse * * @return void */ public function api($request = null, $response = null, $sendResponse = true) { $this->klein->respond('POST', '/authenticate', $this->authenticate); $this->klein->onHttpError($this->handleError); // see https://github.com/klein/klein.php/wiki/Sub-Directory-Installation if ($request === null) { $request = Request::createFromGlobals(); } // Grab the server-passed "REQUEST_URI" $uri = $request->server()->get('REQUEST_URI'); // Set the request URI to a modified one (without the "subdirectory") in it $request->server()->set('REQUEST_URI', '/' . substr($uri, strlen($this->configuration['basePath']))); // Pass our request to our dispatch method $this->klein->dispatch($request, $response, $sendResponse); }
public function dispatch() { $params = $this->parameters; // ---- services ---- $this->routing->respond(function ($request, $response, $service, $app) use($params) { // set this site's title $app->title = 'Lunchsite'; // add a custom validator (all amounts need to be positive floats) $service->addValidator('positiveFloat', function ($str) { return preg_match('/^([0-9]+)([\\.0-9]+)?$/', $str); }); // -- Lazy stored database $app->register('connection', function () use($params) { $db_address = join(';', array('host=' . $params['db_host'], 'port=' . $params['db_port'], 'dbname=' . $params['db_name'])); $db = new ezSQL_pdo('mysql:' . $db_address, $params['db_user'], $params['db_pass']); /* // Cache expiry $db->cache_timeout = 1; // in hours // Specify a cache dir. Path is taken from calling script $db->cache_dir = 'ezsql_cache'; // (1. You must create this dir. first!) // (2. Might need to do chmod 775) // Global override setting to turn disc caching off // (but not on) $db->use_disk_cache = true; // By wrapping up queries you can ensure that the default // is NOT to cache unless specified $db->cache_queries = true; */ return $db; }); // -- Lazy load the repositories (not all are needed for every single request) $app->register('transactionController', function () { return new TransactionController(); }); // -- Lazy load the repositories (not all are needed for every single request) $app->register('accountRepository', function () use($app) { return new AccountRepository($app->connection); }); $app->register('dashboardRepository', function () use($app) { return new DashboardRepository($app->connection); }); $app->register('transactionRepository', function () use($app) { return new TransactionRepository($app->connection); }); // -- Lazy stored initialized twig engine $app->register('twig', function () use($params) { $useCache = $params['twig_use_cache']; $paths = $this->getFolders($params['paths']['twig']); $loader = new Twig_Loader_Filesystem($paths); $twig = new Twig_Environment($loader, array('cache' => $useCache ? $params['paths']['cache'] : false)); TwigExtensions::addExtensions($twig); return $twig; }); }); // ---- root ---- $this->routing->respond('GET', '/?', function ($request, $response, $service, $app) { $data = array('app' => $app, 'testData' => $app->dashboardRepository->getUserTotals2(), 'userData' => $app->dashboardRepository->getUserTotals(), 'totalCash' => $app->dashboardRepository->getTotalCash(), 'totalBank' => $app->dashboardRepository->getTotalBank(), 'lunchAccount' => $app->accountRepository->getLunchpotAccount(), 'accounts' => $app->accountRepository->getAccounts(), 'transactions' => $app->transactionRepository->findAll(true), 'transactionTypes' => $app->transactionRepository->getTransactionTypes()); return $app->twig->render('dashboard.html.twig', $data); }); $this->routing->respond('GET', '/ng/?', function ($request, $response, $service, $app) { $response->file('/ng/index.html'); }); /*$this->routing->respond('GET', '/ng/.+', function ($request, $response, $service, $app) { return $response->file(__DIR__ . $request->pathname()); });*/ // ---- transaction ---- /*foreach(array('TransactionController') as $controller) { $controller = preg_replace('/^(.+)Controller$/', '$1', $controller); // Include all routes defined in a file under a given namespace $klein->with("/$controller", "controller/$controller.php"); }*/ $this->routing->respond('POST', '/transaction/[create|read|update|delete:action]', function ($request, $response, $service, $app) { return $app->transactionController->{$request->action . 'Action'}($request, $response, $service, $app); }); // ---- account ---- $this->routing->respond('GET', '/account/[i:id]', function ($request, $response, $service, $app) { $data = array('account' => $app->accountRepository->getAccountById($request->id)); return $app->twig->render('account.html.twig', $data); }); // -- Handle errors $this->routing->onHttpError(function ($code, $router) { $app = $router->app(); switch ($code) { case 400: $response = $app->twig->render('400-bad-request.html.twig'); $router->response()->body($response); break; case 403: $response = $app->twig->render('403-forbidden.html.twig'); $router->response()->body($response); break; case 404: $response = $app->twig->render('404-not-found.html.twig'); $router->response()->body($response); break; case 405: $router->response()->json(array('code' => $code, 'status' => 'Method Not Allowed')); break; default: $router->response()->body('Oh no, a bad error happened that caused a ' . $code); } }); $this->routing->dispatch(); }
public function dispatch() { $request = \Klein\Request::createFromGlobals(); foreach ($this->middleware as $middleware) { if (!$middleware->dispatch($request)) { return; } } parent::dispatch($request, $response); }
/** * Listen to the defined routes */ public function listen() { $this->router->dispatch(); }
public function doRoute() { $klein = new Klein(); $this->config = new Config("../app/config/app.php"); $klein->respond("GET", $this->homePath, function () { $controller = new Home(new View\Home()); $controller->index(); }); $klein->respond("GET", $this->loginPath . "?", function ($request, $response) { $url = $this->auth->index(); $response->redirect($url); }); $klein->respond("GET", "/github-callback/?", function ($request, $response) { if ($request->code) { $this->auth->getToken($request->code); return $response->redirect($this->userPath); } return $response->redirect($this->homePath); }); $klein->respond("GET", $this->userPath . "?", function ($request, $response) { $session = new Session(); $token = $session->get($this->auth->getTokenSessionName()); if ($token) { return $this->auth->loggedInUser($token); } return $response->redirect($this->homePath); }); $klein->respond("GET", $this->logoutPath . "?", function ($request, $response) { $session = new Session(); $session->destroy($this->auth->getTokenSessionName()); return $response->redirect($this->homePath); }); $klein->with($this->usersPath, function () use($klein) { $klein->respond("GET", "/?", function ($request, $response) { $controller = new Users(); $controller->index($request->fetchFromID); }); $klein->respond("GET", "/[:username]/?", function ($request, $response) { $controller = new Users(); $controller->show($request->username); }); }); $klein->respond("GET", $this->searchPath . "?", function ($request, $response) { $controller = new Users(); $controller->search(); }); $klein->respond("GET", $this->followPath . "[:username]/?", function ($request, $response) { $controller = new Users(); $controller->follow($request->username); }); $klein->respond("GET", $this->unFollowPath . "[:username]/?", function ($request, $response) { $controller = new Users(); $controller->unFollow($request->username); }); $klein->respond("404", function ($request) { $page = $request->uri(); $controller = new Error(new View\Error()); $controller->pageNotFoundError($page); }); $klein->onError(function ($klein, $err_msg) { if ($this->config->get("DEBUG") === true) { throw new \Exception($err_msg); } else { $controller = new Error(new View\Error()); $controller->serverError(); error_log($err_msg, 3, $this->config->get("ERROR_LOG")); } }); $klein->dispatch(); }
namespace ksv\trouble; date_default_timezone_set('America/Sao_Paulo'); require_once __DIR__ . '/../vendor/autoload.php'; require 'Base.php'; require 'User.php'; require 'Config.php'; require 'Db.php'; require 'TemplateEngine.php'; use Klein\Klein; error_reporting(getenv('ENV') === 'production' ? 0 : E_ALL); $router = new Klein(); $router->respond(function ($req, $res, $svc, $app) { $app->register('config', function () { return new Config(); }); $app->register('db', function () use($app) { return new Db($app); }); $app->register('user', function () use($app) { return new User($app); }); $app->register('template', function () use($app) { return new TemplateEngine($app); }); }); foreach (require 'routes.php' as $route) { $router->respond($route->path, $route->method, $route->handler); } $router->dispatch();
$mime = "image/jpeg"; break; case "png": $mime = "image/png"; break; } $response->file(realpath("./src/Checklist/Views/Static/" . $trailRaw), $name, $mime); return; } $controller = str_replace('Home', ucfirst(strtolower($request->param('controller', 'home'))), HomeController::class); if (count($trail) > 0) { $action = array_shift($trail); } else { $action = "index"; } $body = call_user_func_array([new $controller($response, $app, $service), $action], $trail); $response->body($body); }); $klein->onHttpError(function ($code, Klein $router) { switch ($code) { case 404: $router->response()->body('Oops! These are not the droids you are looking for.'); $router->response()->dump($router); break; } }); $klein->dispatch(); // TODO: Add DI // TODO: object(className)? // TODO: Add db connection (may fs based db) // TODO: Add Angular
$module_files = utilities::glob_recursive($module_root . "*.php", GLOB_NOSORT); foreach ($module_files as $mfile) { $modules[] = (include $mfile); } foreach ($modules as $mj) { if (utilities::module_valid($mj)) { $app->respond($mj['methods'], $mj['route'], function (\Klein\Request $request, \Klein\Response $response) use($mj) { /* TODO: check callback access */ $answer = $mj['callback']($mj, $request, $response); if ($mj['response_type'] === "object") { $response_json = array("result" => array("code" => $answer['code'], "object" => $answer['object']), "data" => $answer['data']); return $response->json($response_json); } else { if ($mj['response_type'] === "array") { $response_json = array("result" => array("code" => $answer['code'], "object" => $answer['object']), "pagination" => array("window" => $answer['window'], "current" => $answer['current'], "next" => $answer['next'], "total" => $answer['total'], "pages" => $answer['pages']), "data" => $answer['data']); return $response->json($response_json); } else { if ($mj['response_type'] == "file") { } } } }); } else { } } $app->onError(function (\Klein\Klein $app, $message, $type, jsonui_exception $ex) { /** TODO: save report */ return $app->response()->json(array("result" => array("code" => $ex->getCode(), "message" => $ex->getMessage()))); }); $app->dispatch();
$route->respond('GET', '/dashboard/show', function ($request, $response) use($dashboard) { return $dashboard->show($request, $response); }); $route->respond('GET', '/dashboard/delete/[i:id]', function ($request, $response) use($dashboard) { return $dashboard->delete($request, $response); }); $route->respond('GET', '/dashboard/edit/[i:id]', function ($request, $response) use($dashboard) { return $dashboard->edit($request, $response); }); $route->respond('POST', '/dashboard/edit/[i:id]', function ($request, $response) use($dashboard) { return $dashboard->update($request, $response); }); $route->respond('GET', '/dashboard/leave/index', function ($request, $response) use($leave) { return $leave->index($request, $response); }); $route->respond('GET', '/dashboard/leave/create', function ($request, $response) use($leave) { return $leave->create($request, $response); }); $route->respond('POST', '/dashboard/leave/create', function ($request, $response) use($leave) { return $leave->store($request, $response); }); $route->respond('GET', '/dashboard/leave/approve/[i:id]', function ($request, $response) use($leave) { return $leave->approve($request, $response); }); // $rotue->respond('GET', '/posts', $callback); // $rotue->respond('POST', '/posts', $callback); // $rotue->respond('PUT', '/posts/[i:id]', $callback); // $rotue->respond('DELETE', '/posts/[i:id]', $callback); // $rotue->respond('OPTIONS', null, $callback); $route->dispatch();