function jsonp($x) { Slim::response()->header('Content-Type', 'application/json'); if (array_key_exists('callback', $_GET)) { return preg_replace("/[^a-zA-Z0-9]/", "", $_GET['callback']) . '(' . json_encode($x) . ')'; } else { return json_encode($x); } }
// 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) { global $referrers; $request = $app->request();
require_once "../vendor/autoload.php"; $dsn = "mysql:dbname=slimtut;host=localhost"; $username = "******"; $password = "******"; $pdo = new PDO($dsn, $username, $password); $db = new NotORM($pdo); $app = new Slim(array("MODE" => "development", "TEMPLATES.PATH" => "./templates")); $app->get("/", function () { echo "<h1>Hello Slim World</h1>"; }); $app->get("/books", function () use($app, $db) { $books = array(); foreach ($db->books() as $book) { $books[] = array("id" => $book["id"], "title" => $book["title"], "author" => $book["author"], "summary" => $book["summary"]); } $app->response()->header("Content-Type", "application/json"); echo json_encode($books); }); $app->get("/book/:id", function ($id) use($app, $db) { $app->response()->header("Content-Type", "application/json"); $book = $db->books()->where("id", $id); if ($data = $book->fetch()) { echo json_encode(array("id" => $data["id"], "title" => $data["title"], "author" => $data["author"], "summary" => $data["summary"])); } else { echo json_encode(array("status" => false, "message" => "Book ID {$id} does not exist")); } }); $app->post("/book", function () use($app, $db) { $app->response()->header("Content-Type", "application/json"); $book = $app->request()->post(); $result = $db->books->insert($book);
/** * Sets the status to zero and outputs some error json * @param Slim $app The app reference * @param String $message The message we wish to output * @param integer $status The error code (HTTP) */ function json_error($app, $message, $status = 400) { $app->response()->status($status); json(array('error' => $message)); }
/** * Set ETag HTTP Response Header * * Set the etag header and stop if the conditional GET request matches. * The `value` argument is a unique identifier for the current resource. * The `type` argument indicates whether the etag should be used as a strong or * weak cache validator. * * When the current request includes an 'If-None-Match' header with * a matching etag, execution is immediately stopped. If the request * method is GET or HEAD, a '304 Not Modified' response is sent. * * @param string $value The etag value * @param string $type The type of etag to create; either "strong" or "weak" * @throws InvalidArgumentException If provided type is invalid */ public static function etag($value, $type = 'strong') { //Ensure type is correct if (!in_array($type, array('strong', 'weak'))) { throw new InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".'); } //Set etag value $value = '"' . $value . '"'; if ($type === 'weak') { $value = 'W/' . $value; } Slim::response()->header('ETag', $value); //Check conditional GET if ($etagsHeader = Slim::request()->header('IF_NONE_MATCH')) { $etags = preg_split('@\\s*,\\s*@', $etagsHeader); if (in_array($value, $etags) || in_array('*', $etags)) { Slim::raise(304); } } }
/** * Slim's response object * * @return \Slim\Http\Response */ protected function response() { return $this->app->response(); }
/** * Test custom error handler uses existing Response object */ public function testErrorHandlerUsesCurrentResponseObject() { $s = new Slim(array('debug' => false)); $s->error(function (Exception $e) use($s) { $r = $s->response(); $r->status(503); $r->write('Foo'); $r['X-Powered-By'] = 'Slim'; echo 'Bar'; }); $s->get('/bar', function () { throw new Exception('Foo'); }); $s->call(); list($status, $header, $body) = $s->response()->finalize(); $this->assertEquals(503, $status); $this->assertEquals('FooBar', $body); $this->assertEquals('Slim', $header['X-Powered-By']); }
<?php require_once dirname(__DIR__) . '/bootstrap.php'; require_once PATH_VENDOR_ROOT . '/Slim/Slim.php'; $app = new Slim(); $app->config('templates.path', dirname(__DIR__) . '/templates'); $app->get('/', function () use($app) { $app->render('index.html', array()); }); $app->get('/mecab', function () use($app) { $sentence = $app->request()->get('s'); $cl = new ClassLoader(); $ret = $cl->load('Mecab'); $mecab = new Mecab(); /* $mecab_options = array( '-u' => PATH_RESOURCE_ROOT . '/word.dic', ); */ $ret = $mecab->parseToNode($sentence, $mecab_options); $app->response()->header('Content-Type', 'application/json; charset=utf-8'); $app->response()->body(json_encode($ret)); }); $app->run();
<?php require_once __DIR__ . '/../vendor/autoload.php'; // Prepare app $app = new Slim(array('negotiation.enabled' => true)); // Setup routes $app->get('/', function () use($app) { $format = $app->respondTo('html', 'rdf', 'ttl', 'json', 'nt'); switch ($format) { case 'html': return $app->redirect('http://www.aelius.com/njh/', 303); default: $rootUrl = $app->request()->getUrl() . $app->request()->getScriptName(); return $app->redirect("{$rootUrl}/foaf.{$format}", 303); } }); $app->get('/foaf:format', function () use($app) { $format = $app->respondTo('rdf', 'ttl', 'json', 'nt'); $uri = $app->request()->getUrl() . $app->request()->getPath(); $foaf = new EasyRdf_Graph($uri); $foaf->parseFile(__DIR__ . '/../data/foaf.ttl', 'turtle', $uri); $app->response()->body($foaf->serialise($format)); }); // Run app $app->run();
<?php define('AUTHCOOKIE', 'superblorg'); use Infrastructure\Persistence\Doctrine\UnitOfWork; use Presentation\Services\SlimAuthenticationService; use Infrastructure\Persistence\Doctrine\UserRepository; use Domain\UserAuthenticator; use Domain\PasswordHasher; $app = new Slim(array('view' => 'TwigView', 'templates.path' => dirname(dirname(__FILE__)) . DS . 'Views')); //common objects $unitOfWork = new UnitOfWork(); $userRepo = new UserRepository(); $authService = new SlimAuthenticationService($app, $userRepo, new UserAuthenticator($userRepo, new PasswordHasher())); $app->hook('slim.before', function () use($app, $authService, $unitOfWork) { if (!$authService->isAuthenticated(AUTHCOOKIE)) { $app->response()->redirect('/login', 303); } if ($user = $authService->getLoggedInUser(AUTHCOOKIE)) { $authService->regenerateUserCookie(AUTHCOOKIE, $user); } $unitOfWork->begin(); }); $app->hook('slim.after', function () use($app, $unitOfWork) { $unitOfWork->commit(); });
/** * Test that app returns 404 response when there are no matching routes */ public function testNotFoundIfNoMatchingRoutes() { $_SERVER['REQUEST_URI'] = "/foo"; $_SERVER['REQUEST_METHOD'] = 'GET'; $app = new Slim(); $app->map('/foo/bar', function () { echo "Foo bar!"; })->via('GET'); $app->run(); $this->assertEquals(404, $app->response()->status()); }
<?php /** * index.php. This file contains all the backend functions that run the website * Uses Slim framework. */ require 'Slim/Slim.php'; $app = new Slim(); //Sets up the links to the functions $app->get('/', function () use($app) { $response = $app->response(); $response->status(200); $response->write('The API is working'); }); /** * Add a scan result */ $app->post('/AddScanResults', 'addScanResults'); $app->get('/Vertices', 'getVertices'); $app->get('/Test/:userId', 'getTest'); $app->get('/Data', 'getAllData'); $app->get('/DataAverage', 'getDataAverage'); $app->get('/DataCount', 'getCountData'); $app->get('/DataNoDirection', 'getDataNoDirection'); $app->run(); function getTest($userId) { echo $userId; } /** * A function to add a class
// Models require 'models/Article.php'; // Configuration TwigView::$twigDirectory = __DIR__ . '/vendor/twig/twig/lib/Twig/'; ORM::configure('odbc:DRIVER={SQL Server};SERVER=sp7877nt106;DATABASE=7141_5;'); ORM::configure('username', 'user_7141'); ORM::configure('password', 'user_7141'); // Start Slim. $app = new Slim(array('view' => new TwigView())); // Auth Check. $authCheck = function () use($app) { $authRequest = isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); $authUser = $authRequest && $_SERVER['PHP_AUTH_USER'] === USERNAME; $authPass = $authRequest && $_SERVER['PHP_AUTH_PW'] === PASSWORD; if (!$authUser || !$authPass) { $app->response()->header('WWW-Authenticate: Basic realm="My Blog Administration"', ''); $app->response()->header('HTTP/1.1 401 Unauthorized', ''); $app->response()->body('<h1>Please enter valid administration credentials</h1>'); $app->response()->send(); exit; } }; // 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();
require 'vendor/autoload.php'; include 'vendor/notorm/notorm/NotORM.php'; $dsn = 'sqlite:' . realpath('./data/db.sqlite'); $pdo = new PDO($dsn); $db = new NotORM($pdo); $app = new Slim(array('MODE' => 'development', 'TEMPLATES.PATH' => './templates')); $app->get('/', function () { echo '<h1>Hello Slim World</h1>'; }); $app->get('/books', function () use($app, $db) { $books = array(); foreach ($db->books() as $book) { $books[] = array('id' => $book['id'], 'title' => $book['title'], 'author' => $book['author'], 'summary' => $book['summary']); } $app->response()->header('Content-Type', 'application/json'); echo json_encode($books); }); $app->get('/book/:id', function ($id) use($app, $db) { $app->response()->header('Content-Type', 'application/json'); $book = $db->books()->where('id', $id); if ($data = $book->fetch()) { echo json_encode(array('id' => $data['id'], 'title' => $data['title'], 'author' => $data['author'], 'summary' => $data['summary'])); } else { echo json_encode(array('status' => false, 'message' => 'Book ID ' . $id . ' does not exist')); } }); $app->post('/book', function () use($app, $db) { $app->response()->header('Content-Type', 'application/json'); $book = $app->request()->post(); $result = $db->books->insert($book);
/** * Test that app sends response with custom HTTP version */ public function testAppSendsResponseWithCustomHttpVersion() { $app = new Slim(array('http.version' => '1.0')); $app->get('/', function () { }); $app->run(); $this->assertEquals('1.0', $app->response()->httpVersion()); }
Slim::init(); /*** CALLBACKS ***/ //Register a "before" callback for PHP >=5.3 Slim::before(function () { Slim::response()->write('<p>Before!</p>'); }); //Register a "before" callback for PHP <5.3 /* Slim::before('example_before'); function example_before() { Slim::response()->write('Before!'); } */ //Register an "after" callback for PHP >=5.3 Slim::after(function () { Slim::response()->write('<p>After!</p>'); }); //Register an "after" callback for PHP <5.3 /* Slim::after('example_after'); function example_after() { Slim::response()->write('After!'); } */ /*** ROUTES ***/ //Sample GET route for PHP >=5.3 Slim::get('/', function () { Slim::render('index.php'); }); //Sample GET route for PHP <5.3 /*
/** * Test Slim returns 200 OK for successful route * * Pre-conditions: * You have initialized a Slim app with an accessible route that * does not throw any Exceptions and does not set a custom status. * * Post-conditions: * The response status is 200 and response body is as expected. */ public function testSlimOkResponse() { Slim::init(); Slim::get('/', function () { echo "Ok"; }); Slim::run(); $this->assertEquals(Slim::response()->status(), 200); $this->assertEquals(Slim::response()->body(), 'Ok'); }
/** * Constructor * * @param Slim $app * @return void */ public function __construct(\Slim\Slim $app) { $this->app = $app; $this->app->contentType('application/json'); $this->response = $this->app->response(); }