/** * Constructor * * @param $slim Object of slim * @param $markdown bool */ public function __construct(Slim $slim) { $slim->notFound(function () use($slim) { $slim->view()->setLayout($slim->config('layout.file') . '.php'); $slim->render("404"); }); $this->slim = $slim; $this->init(); }
// blog pagination $blog->get('/blog/:number', function ($number) use($blog, $getMarkdownPosts) { // get our posts $posts = $getMarkdownPosts($blog->config('posts.path')); // determine the start position of the array $previous_page = $number - 1; $start_index = $previous_page * $blog->config('pagination'); // limit our posts to pagination $posts_limit = array_slice($posts, $start_index, $blog->config('pagination')); // get the total number of posts $posts_count = count($posts); // calculate the number of page $pages_number = ceil($posts_count / $blog->config('pagination')); // if the requested page is too high, 401 if ($number > $pages_number) { $blog->notFound(); } $blog->render('index.html', array('posts' => $posts_limit, 'page_current' => $number, 'page_count' => $pages_number)); })->conditions(array('number' => '\\d+')); // blog index $blog->get('/blog', function () use($blog) { $blog->redirect('/'); }); // post view $blog->get('/blog/:post', function ($post) use($blog) { // get the posts director, and post filename $dir = $blog->config('posts.path'); $post = $post . '.md'; $post_path = $dir . '/' . $post; // if the post doesn't exists, 404 redirect if (!file_exists($post_path)) {
$cl_scraper = new CraigListScraper("sites/{$loadConfiguration}"); $title = $cl_scraper->getInfo()->title; require 'templates/index.php'; } catch (Exception $e) { echo $e->getMessage(); } }); $app->get('/site/:site/data', function ($site) use($app, $sites) { $init = true; $loadConfiguration = "findjobs.locations.xml"; if (isset($sites[$site])) { $loadConfiguration = "{$site}.locations.xml"; $sites[$site] = true; } else { $app->redirect('/'); } try { require 'lib/CraigListScraper.class.php'; $cl_scraper = new CraigListScraper("sites/{$loadConfiguration}"); $json_results = array('page_info' => $cl_scraper->getInfo(), 'region_list' => $cl_scraper->getRegions(), 'area_list' => $cl_scraper->getAreas(), 'form_fields' => $cl_scraper->getFields()); header('Content-type: application/json'); echo json_encode($json_results); exit; } catch (Exception $e) { echo $e->getMessage(); } }); $app->notFound(function () use($app) { $app->redirect('/'); }); $app->run();
<?php // Initialize flags, config, models, cache, etc. require_once 'init.php'; require_once BASE_DIR . '/vendor/Slim/Slim/Slim.php'; require_once BASE_DIR . '/vendor/Slim-Extras/Log Writers/TimestampLogFileWriter.php'; $app = new Slim(array('mode' => defined('PRODUCTION') ? 'production' : 'development', 'debug' => false, 'log.enabled' => true, 'log.writer' => new TimestampLogFileWriter(array('path' => BASE_DIR, 'name_format' => '\\s\\l\\i\\m\\_\\l\\o\\g')))); $app->configureMode('development', function () use($app) { $app->config(array('debug' => true)); }); $app->configureMode('production', function () use($app) { error_reporting(0); $app->notFound(function () use($app) { $page = new ErrorController(404); $page->render(); }); $app->error(function (Exception $e) use($app) { $app->response()->status(500); if (!$app->request()->isAjax()) { $page = new ErrorController(500); $page->render(); } $app->stop(); if (file_exists(BASE_DIR . '/.gbemail')) { foreach (explode('\\n', file_get_contents(BASE_DIR . '/.gbemail')) as $email) { mail(trim($email), "GetchaBooks Error", get_error_message($e)); } } }); }); $app->hook('slim.before', function () use($app) {
/** * Test custom Not Found handler */ public function testNotFound() { $s = new Slim(); $s->notFound(function () { echo "Not Found"; }); $s->get('/foo', function () { }); $s->call(); list($status, $header, $body) = $s->response()->finalize(); $this->assertEquals(404, $status); $this->assertEquals('Not Found', $body); }
/** * Run the Slim app * * This method is the "meat and potatoes" of Slim and should be the last * method you call. This fires up Slim, routes the request to the * appropriate callback, then returns a response to the client. * * This method will also invoke the NotFound handler if no matching * routes are found. This method will also catch any Exceptions * thrown by Slim::raise or by application errors. */ public static function run() { try { self::runCallables(self::$app->before); ob_start(); if (!self::router()->dispatch()) { Slim::notFound(); } self::response()->write(ob_get_clean()); self::runCallables(self::$app->after); self::response()->send(); } catch (Exception $e) { ob_clean(); if ($e instanceof SlimException) { $status = $e->getCode(); $body = $e->getMessage(); } else { $status = 500; $body = self::generateErrorMarkup($e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()); } self::response()->status($status); self::response()->body($body); self::response()->send(); } }
/** * Test custom Not Found handler */ public function testNotFound() { $s = new Slim(); $s->notFound(function () { echo "Not Found"; }); $s->get('/foo', function () { }); $env = $s->environment(); list($status, $header, $body) = $s->call($env); $this->assertEquals(404, $status); $this->assertEquals('Not Found', $body); }
/** * Test Slim Not Found handler * * Pre-conditions: * Initialize one Slim app without custom Not Found handler; * Initialize one Slim app with custom Not Found Handler; * Both app's routes do not match HTTP request; * * Post-conditions: * Both Slim apps' response status is 404; * Custom Not Found handler is invoked if specified; */ public function testSlimRouteNotFound() { $app1 = new Slim(); $app1->get('/foo', function () { }); ob_start(); $app1->run(); $app1Out = ob_get_clean(); $app2 = new Slim(); $app2->notFound(function () { echo 'Not Found'; }); $app2->get('/bar', function () { }); ob_start(); $app2->run(); $app2Out = ob_get_clean(); $this->assertEquals(404, $app1->response()->status()); $this->assertEquals(404, $app2->response()->status()); $this->assertEquals('Not Found', $app2->response()->body()); }
/** * Set Application routes based on the routes specified in config * Also sets layout file if it's enabled for that specific route */ public function setRoutes() { $this->_routes = $this->config('routes'); $self = $this; $prefix = $self->slim->config('prefix'); foreach ($this->_routes as $key => $value) { $this->slim->map($prefix . $value['route'], function () use($self, $key, $value) { $args = func_get_args(); $layout = isset($value['layout']) ? $value['layout'] : true; if (!$layout) { $self->enableLayout = false; } else { $self->setLayout($layout); } $self->slim->view()->appendGlobalData(array("route" => $key)); $template = $value['template']; //set view data for article and archives routes switch ($key) { case '__root__': case 'rss': case 'atom': $self->allArticles = array_slice($self->allArticles, 0, 10); break; case 'article': $article = $self->setArticle($self->getPath($args)); $template = isset($article['meta']['template']) && $article['meta']['template'] != "" ? $article['meta']['template'] : $template; break; case 'archives': $self->loadArchives($args); break; case 'category': case 'tag': $self->filterArticles($key, $args[0]); break; } // render the template file $self->render($template); })->via('GET')->name($key)->conditions(isset($value['conditions']) ? $value['conditions'] : array()); } // load all articles // This isn't necessary for route to an article though // will help to generate tag cloud/ category listing $self->loadArticles(); // Register not found handler $this->slim->notFound(function () use($self) { $self->slim->render('404'); }); }
// create a log channel $log = new Logger('name'); $log->pushHandler(new StreamHandler('log/your.log', Logger::WARNING)); // add records to the log $log->addWarning('Foo'); $log->addError('Bar'); // Blog Home. $app->get('/', function () use($app) { $articles = Model::factory('Article')->order_by_desc('timestamp')->find_many(); return $app->render('blog_home.html', array('articles' => $articles)); }); // Blog View. $app->get('/view/(:id)', function ($id) use($app) { $article = Model::factory('Article')->find_one($id); if (!$article instanceof Article) { $app->notFound(); } return $app->render('blog_detail.html', array('article' => $article)); }); // Admin Home. $app->get('/admin', $authCheck, function () use($app) { $articles = Model::factory('Article')->order_by_desc('timestamp')->find_many(); return $app->render('admin_home.html', array('articles' => $articles)); }); // Admin Add. $app->get('/admin/add', $authCheck, function () use($app) { return $app->render('admin_input.html', array('action_name' => 'Add', 'action_url' => '/microframework/admin/add')); }); // Admin Add - POST. $app->post('/admin/add', $authCheck, function () use($app) { $article = Model::factory('Article')->create();
if (!isset($post['of']) || trim($post['of']) == "" || $post['of'] == 0 || $post['of'] == "0" || !is_numeric($post['of'])) { $of = "?"; } else { $of = $post['of']; } if ($teams == "?" && $of == "?") { $params['teams'] = App::teamsForEvent($id, "2", "?"); } else { $params['teams'] = App::teamsForEvent($id, $teams, $of); } } } } $params['id'] = $id; $params['errors'] = array(); $app->render('app.tpl', $params); })->via('GET', 'POST'); $app->get('/error/(:code)/', function ($code) use($app) { if (isset($code) && $code != null) { $app->render('error.tpl', array('code' => $code)); } else { $app->render('error.tpl'); } }); $app->notFound(function () use($app) { $app->redirect("/error/404/"); }); $app->error(function (Exception $e) use($app) { $app->notFound(); }); $app->run();
/** * Run the Slim app * * This method is the "meat and potatoes" of Slim and should be the last * method you call. This fires up Slim, routes the request to the * appropriate callback, then returns a response to the client. * * This method will invoke the NotFound handler if no matching * routes are found. * * @return void */ public static function run() { try { self::runCallables(self::$app->before); ob_start(); if (!self::router()->dispatch()) { Slim::notFound(); } self::response()->write(ob_get_clean()); self::runCallables(self::$app->after); self::response()->send(); } catch (SlimRequestSlashException $e) { self::redirect(self::request()->root . self::request()->resource . '/', 301); } }
/** * Set Application routes based on the routes specified in config * Also sets layout file if it's enabled for that specific route */ public function setRoutes() { $this->_routes = $this->getConfig('routes'); $self = $this; $prefix = $this->getConfig('prefix'); foreach ($this->_routes as $key => $value) { $this->slim->map($prefix . $value['route'], function () use($self, $key, $value) { $args = func_get_args(); $layout = isset($value['layout']) ? $value['layout'] : true; // This will store a custom function if defined into the route $custom = isset($value['custom']) ? $value['custom'] : false; $self->slim->view()->appendGlobalData(array("route" => $key)); $template = isset($value['template']) ? $value['template'] : false; //set view data for article and archives routes switch ($key) { case '__root__': case 'rss': case 'atom': $self->allArticles = array_slice($self->allArticles, 0, 10); break; case 'sitemap': $self->slim->response->headers->set('Content-Type', 'text/xml'); $self->setSitemapData(); break; case 'article': $article = $self->setArticle($self->getPath($args)); $template = $article->getMeta('template') && $article->getMeta('template') != "" ? $article->getMeta('template') : $template; break; case 'archives': $self->loadArchives($args); break; case 'category': case 'tag': $self->filterArticles($key, $args[0]); break; // If key is not matched, check if a custom function is declared // If key is not matched, check if a custom function is declared default: if ($custom && is_callable($custom)) { call_user_func($custom, $self, $key, $value); } break; } if (!$layout) { $self->enableLayout = false; } else { $self->setLayout($layout); } // render the template file $self->render($template); })->via('GET')->name($key)->conditions(isset($value['conditions']) ? $value['conditions'] : array()); } // Register not found handler $this->slim->notFound(function () use($self) { $self->slim->render('404'); }); }
<?php ob_start("ob_gzhandler"); header('Content-type: application/json'); require_once "../include_me.php"; require 'Slim/Slim.php'; $app = new Slim(); /** * Set Custom 404 page when an API method is not found */ $app->notFound(function () use($app) { $app->render("api404.html"); }); /** * Set Custom Error Page. No sensetive information should be displayed to the user */ $app->error(function () use($app) { // log error //$app -> render("apiError.html"); }); /** * REST Methods */ $app->get('/teacher/', function () use($teacherModel) { $result = $teacherModel->get(); echo json_encode($result); }); $app->get('/course/', function () use($courseModel) { $result = $courseModel->get(); echo json_encode($result); });