本文整理汇总了PHP中Slim::response方法的典型用法代码示例。如果您正苦于以下问题:PHP Slim::response方法的具体用法?PHP Slim::response怎么用?PHP Slim::response使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Slim
的用法示例。
在下文中一共展示了Slim::response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: jsonp
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);
}
}
示例2: Slim
// 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();
示例3: PDO
require_once "../vendor/autoload.php";
$dsn = "mysql:dbname=slimtut;host=localhost";
$username = "dbuser";
$password = "dbpass";
$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);
示例4: json_error
/**
* 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));
}
示例5: etag
/**
* 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);
}
}
}
示例6: response
/**
* Slim's response object
*
* @return \Slim\Http\Response
*/
protected function response()
{
return $this->app->response();
}
示例7: testErrorHandlerUsesCurrentResponseObject
/**
* 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']);
}
示例8: dirname
<?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();
示例9: Slim
<?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();
示例10: Slim
<?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();
});
示例11: testNotFoundIfNoMatchingRoutes
/**
* 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());
}
示例12: getTest
<?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
示例13: Slim
// 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();
示例14: realpath
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);
示例15: testAppSendsResponseWithCustomHttpVersion
/**
* 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());
}