<?php require 'vendor/autoload.php'; require 'plugins/NotORM.php'; require 'config/dbconnect.php'; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Dflydev\FigCookies\Cookie; use Dflydev\FigCookies\FigRequestCookies; use Dflydev\FigCookies\SetCookie; $app = new \Slim\App(); require 'api/v1/Auht.php'; require 'api/v1/Article.php'; require 'api/v1/Offer.php'; require 'api/v1/Categories.php'; require 'api/v1/AppUser.php'; $app->get('/', function ($request, $response) { $app = $response->withStatus(200)->withHeader('Content-Type', 'application/json')->withHeader('Access-Control-Allow-Origin', '*'); $result = 'Сервер запущен'; echo json_encode($result, JSON_UNESCAPED_UNICODE); return $app; }); $app->run();
public function instantiate($dao) { // Instantiate a Slim application: $app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]); // Routes $app->get('/api/posts/{id}', function (ServerRequestInterface $request, ResponseInterface $response, $args) use($dao) { $params = $request->getQueryParams(); $id = $args['id']; $post = $dao->getPost($id); if (!empty($post[0])) { $postResponse = ["post" => $post[0]]; } else { // send an empty json list {} and not [] $postResponse = ["post" => new ArrayObject()]; } $response->getBody()->write(json_encode($postResponse, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE)); $response = $response->withHeader('Content-type', 'application/json'); return $response; }); $app->get('/api/posts', function (ServerRequestInterface $request, ResponseInterface $response) use($dao) { $params = $request->getQueryParams(); if (isset($params['author'])) { $author = $params['author']; } else { $author = null; } // TODO : move in settings $formatDate = 'Y-m-d'; // Date checking if (isset($params['from']) || isset($params['to'])) { if (!DateHelper::validateDate($formatDate, $params['from']) || !DateHelper::validateDate($formatDate, $params['to'])) { throw new Exception("'from' date parameter or 'to' date parameter is not correct or missing."); } else { // pipe concatenation to set h-m-s at 00:00:00 $fromDate = DateTime::createFromFormat($formatDate . '|', $params['from']); $toDate = DateTime::createFromFormat($formatDate . '|', $params['to']); } } else { $fromDate = null; $toDate = null; } $post = $dao->getPosts($author, $fromDate, $toDate); $postResponse = ["posts" => $post, "count" => count($post)]; $response->getBody()->write(json_encode($postResponse, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE)); $response = $response->withHeader('Content-type', 'application/json'); return $response; }); return $app; }
public function run() { $configuration = ['settings' => ['displayErrorDetails' => false]]; $c = new \Slim\Container($configuration); $c['notFoundHandler'] = function ($c) { return function ($request, $response) use($c) { return $c['response']->withStatus(404)->withHeader('Content-type', 'application/json')->write(json_encode(array('status' => 404, 'error' => 'not_found', 'pretty_error' => 'Could not find the specified endpoint.'), JSON_PRETTY_PRINT)); }; }; $c['errorHandler'] = function ($c) { return function ($request, $response) use($c) { return $c['response']->withStatus(500)->withHeader('Content-type', 'application/json')->write(json_encode(array('status' => 404, 'error' => 'internal_error', 'pretty_error' => 'An internal error has occured, please contact the site administrator.'), JSON_PRETTY_PRINT)); }; }; $app = new \Slim\App($c); $app->add(new AuthenticationMiddleware()); $app->get('/oauth/v2/authorize', 'PleioRest\\Controllers\\Authentication::authorize'); $app->post('/oauth/v2/token', 'PleioRest\\Controllers\\Authentication::getToken'); $app->get('/api/users/me', 'PleioRest\\Controllers\\User:me'); $app->post('/api/users/me/register_push', 'PleioRest\\Controllers\\User:registerPush'); $app->post('/api/users/me/deregister_push', 'PleioRest\\Controllers\\User:deregisterPush'); $app->post('/api/users/me/generate_token', 'PleioRest\\Controllers\\User:generateToken'); $app->get('/api/users/me/login_token', 'PleioRest\\Controllers\\User:loginToken'); $app->get('/api', 'PleioRest\\Controllers\\Version:getVersion'); $app->get('/api/doc', 'PleioRest\\Controllers\\Documentation:getDocumentation'); $app->get('/api/doc/swagger', 'PleioRest\\Controllers\\Documentation:getSwagger'); $app->get('/api/sites', 'PleioRest\\Controllers\\Sites:getAll'); $app->get('/api/sites/mine', 'PleioRest\\Controllers\\Sites:getMine'); $app->get('/api/groups', 'PleioRest\\Controllers\\Groups:getAll'); $app->get('/api/groups/mine', 'PleioRest\\Controllers\\Groups:getMine'); $app->get('/api/groups/{guid}/activities', 'PleioRest\\Controllers\\Activities:getGroup'); $app->post('/api/groups/{guid}/activities/mark_read', 'PleioRest\\Controllers\\Activities:markRead'); $app->get('/api/groups/{guid}/events', 'PleioRest\\Controllers\\Events:getGroup'); $app->get('/api/groups/{guid}/members', 'PleioRest\\Controllers\\Members:getGroup'); $app->get('/api/groups/{guid}/files', 'PleioRest\\Controllers\\Files:getGroup'); $app->run(); }
$capsule = new Capsule(); $capsule->addConnection($config['parameters']); $capsule->setAsGlobal(); $capsule->bootEloquent(); $container = new \Slim\Container(['settings' => ['displayErrorDetails' => true]]); //modification de l'erreur 404 $container['notFoundHandler'] = function ($container) { return function ($request, $response) use($container) { return $container['response']->withJson(array("status" => array("error" => "not found")), 404); }; }; //modification de l'erreur 500 $container['errorHandler'] = function ($container) { return function ($request, $response, $exception) use($container) { return $container['response']->withJson(array("status" => array("error" => ['code' => $exception->getCode(), 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => explode("\n", $exception->getTraceAsString())])), 500); }; }; $app = new Slim\App($container); $app->add(new \Slim\Middleware\HttpBasicAuthentication(['path' => ['/command/', '/product/', '/user/', '/banniere/'], 'secure' => false, 'relaxed' => $config['parameters']['hosts_allows'], 'users' => $config['parameters']['api_users']])); //ajout des routes require 'routes/product.php'; require 'routes/command.php'; require 'routes/notification.php'; require 'routes/user.php'; require 'routes/login.php'; require 'routes/other.php'; //redirection vers la doc $app->get('/', function ($request, $response) use($app) { return $response->withRedirect('doc/'); }); $app->run();
<?php /** * Created by PhpStorm. * User: Amedora * Date: 12/10/15 * Time: 10:38 PM */ require 'vendor/autoload.php'; require 'config.php'; $app = new Slim\App(); $app->get('/', function ($request, $response, $args) { $rer = \models\Bus::all(); $response->write(json_encode($rer)); return $response; }); $app->get('/buses/index', function ($request, $response, $args) { $rer = \models\Bus::all(); $response->write(json_encode($rer)); return $response; }); $app->get('/tickets/index', function ($request, $response, $args) { $rer = \models\Tickets::all(); $response->write(json_encode($rer)); return $response; }); $app->get('/tickets/update[/{id}/{status}]', function ($request, $response, $args) { $ticket = \models\Tickets::find($args['id']); $ticket->status = $args['status']; $rer = []; if ($ticket->update()) {
use App\Todo; use App\TodoTransformer; use League\Fractal\Manager; use League\Fractal\Resource\Item; use League\Fractal\Resource\Collection; use League\Fractal\Serializer\ArraySerializer; use League\Fractal\Serializer\DataArraySerializer; date_default_timezone_set("UTC"); $dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load(); $app = new Slim\App(["settings" => ["displayErrorDetails" => true]]); require __DIR__ . "/config/logger.php"; require __DIR__ . "/config/database.php"; $app->add(new \Tuupola\Middleware\Cors(["origin" => "*", "methods" => ["GET", "POST", "PATCH", "DELETE"], "headers.allow" => ["Content-Type", "Accept"], "credentials" => true, "cache" => 86400])); $app->get("/", function ($request, $response, $arguments) { return $response->withStatus(301)->withHeader("Location", "/todos"); }); $app->get("/todos", function ($request, $response, $arguments) { $todos = $this->spot->mapper("App\\Todo")->all(); $fractal = new Manager(); $fractal->setSerializer(new ArraySerializer()); $resource = new Collection($todos, new TodoTransformer()); $data = $fractal->createData($resource)->toArray(); /* Fractal collections are always namespaced. Apparently a feature and */ /* not a bug. Thus we need to return $data["data"] for TodoMVC examples. */ /* https://github.com/thephpleague/fractal/issues/110 */ return $response->withStatus(200)->withHeader("Content-Type", "application/json")->write(json_encode($data["data"], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); }); $app->post("/todos", function ($request, $response, $arguments) { $body = $request->getParsedBody(); $todo = new Todo($body);
# IMPORT require __DIR__ . "/vendor/autoload.php"; use KarabowId\Api\Orm\OrmManager; use KarabowId\Api\ParamHandler; use KarabowId\Api\Messages; # SETUP $configuration = ['settings' => ['displayErrorDetails' => true]]; $config = new \Slim\Container($configuration); $app = new Slim\App($config); $ormManager = new OrmManager(); $app->any("/", function ($request, $response, $args) { $reponse->getBody()->write("No Request Made. Should we throw an exception? or just tell the user to go learn how to consume this api?"); }); # CREATE NEW USER $app->post("/user/new", function ($request, $response, $args) use($app) { return $response; }); # GET USER INFO $app->get("/user", function ($request, $response, $args) use($app) { return $response; }); # MODIFY USER INFO $app->put("/user/edit", function ($request, $response, $args) use($app) { return $response; }); # DELETE USER FROM DB $app->delete("/user/delete", function ($request, $response, $args) use($app) { return $response; }); # RUN $app->run();
* * @link https://freebsd.github.io/redports/ */ namespace Redports\Web; require_once __DIR__ . '/vendor/autoload.php'; $session = new Session(); $app = new \Slim\App(new \Slim\Container(Config::get('slimconfig'))); /* init php-view */ $container = $app->getContainer(); $container['view'] = function ($container) { return new \Slim\Views\PhpRenderer(__DIR__ . '/templates/'); }; /* landing page */ $app->get('/', function ($request, $response, $args) use($session) { return $this->view->render($response, 'index.html', $args); }); /* GitHub OAuth login */ $app->get('/login', function ($request, $response) use($session) { $credentials = new \OAuth\Common\Consumer\Credentials(Config::get('github.oauth.key'), Config::get('github.oauth.secret'), Config::get('github.oauth.redirecturl')); $serviceFactory = new \OAuth\ServiceFactory(); $gitHub = $serviceFactory->createService('GitHub', $credentials, new \OAuth\Common\Storage\Session(), array('user:email', 'public_repo', 'repo:status', 'admin:repo_hook')); $queryParams = $request->getQueryParams(); if (isset($queryParams['code'])) { try { $token = $gitHub->requestAccessToken($queryParams['code']); $result = json_decode($gitHub->request('user'), true); /* TODO: register new user at master if it does not exist yet */ $session->login($result['login']); $_SESSION['name'] = $result['name']; $_SESSION['profile_url'] = $result['html_url'];
<?php require '../vendor/autoload.php'; require 'bootEloquent.php'; use Slim\Views\PhpRenderer; $app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]); $container = $app->getContainer(); $container['view'] = new PhpRenderer(__DIR__ . '/../views/'); $app->get('/', function ($request, $response, $args) { return $this->view->render($response, 'hello.php', ['pessoas' => Pessoa::all()]); }); $app->post('/pessoas', function ($request, $response, $args) { $pessoa = new Pessoa(); $pessoa->nome = $request->getParam('nome'); $pessoa->save(); return $response->withRedirect('/'); }); $app->run();
<?php require 'vendor/autoload.php'; // Create container $container = new \Slim\Container(); // Register component on container $container['view'] = function ($c) { $view = new \Slim\Views\Twig('templates', ['cache' => 'templates']); $view->addExtension(new \Slim\Views\TwigExtension($c['router'], $c['request']->getUri())); return $view; }; $app = new \Slim\App($container); // Define app routes $app->get('/', function ($request, $response, $args) { return $this->view->render($response, 'index.html', ['var1' => 'test']); })->setName('PasteBukket'); $app->get('/api/version/', function ($request, $response, $args) { $data = array("platform" => "pastebukket", "version" => "0.1"); return $response->write(json_encode($data)); }); // Run app $app->run();
<?php require 'vendor/autoload.php'; include_once 'db/dbConnect.php'; include_once 'functions/getters.php'; include_once 'functions/dataHandler.php'; $app = new \Slim\App(); // Default -> redirect on selection page $app->get("/", function ($request, $response, $args) { return $response->withStatus(200)->withHeader('Location', 'rest.php'); }); // select one country, using it's id $app->get("/country/{id}/", function ($request, $response, $args) use($link) { $country = getId($args['id'], 'countries'); if ($country) { return $response->withJson(array("status" => 1, "Id" => $country['id'], "Name" => $country['name'])); } else { $response->withJson(array("status" => 0, "message" => "Country Id {$args['id']} does not exists")); } }); // select one city, using it's id $app->get("/city/{id}/", function ($request, $response, $args) use($link) { $city = getId($args['id'], 'cities'); if ($city) { return $response->withJson(array("status" => 0, "Id" => $city['id'], "Name" => $city['name'])); } else { $response->withJson(array("status" => 1, "message" => "City Id {$args['id']} does not exists")); } }); // select one language, using it's id $app->get("/language/{id}/", function ($request, $response, $args) use($link) {
<?php /** * Created by PhpStorm. * User: RDuuke * Date: 03/11/2015 * Time: 08:07 PM */ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; $app = new Slim\App(); $app->get('/users', '\\RDuuke\\Mdn\\Controllers\\UsersController:index'); $app->post('/users', '\\RDuuke\\Mdn\\Controllers\\UsersController:store'); $app->get('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:show'); $app->put('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:update'); $app->delete('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:destroy'); $app->run();
<?php require_once "../bootstrap.php"; use Symfony\Component\Yaml\Yaml; use Telegram\Bot\Api as TelegramApi; $config = Yaml::parse(file_get_contents('../config.yml')); $telegram = new TelegramApi($config['telegram_api_key']); $app = new \Slim\App(); $app->get('/telegram/webhook/{key}', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) { $key = $request->getAttribute('key'); error_log($request->getBody()); $response->getBody()->write("Hello telegram!"); return $response; }); $app->get('/hello/{name}', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) { $name = $request->getAttribute('name'); $response->getBody()->write("Hello, {$name}"); return $response; })->setName('hello'); $app->get('telegram/setup', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) { global $config, $telegram; $telegramCallbackAuth = $telegram->setWebhook("https://kickbot.telegram.thru.io/telegram/webhook/{$config['telegram_api_key']}"); \Kint::dump($telegramCallbackAuth); exit; }); $app->get('.well-known/acme-challenge/El1K2GOuLyDvjk9-uM8P-Fge_oDMeYHYBL_VVvdvT4s', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) { $response->getBody()->write("El1K2GOuLyDvjk9-uM8P-Fge_oDMeYHYBL_VVvdvT4s.BjQMlU5nwgsexb_DdA7zyb5OWcbghyA_u5G5PCeY610"); return $response; }); $app->run();
use App\Helper\ResponseDataFormatter; use App\Resource\AbstractResource; use Psr\Http\Message\ServerRequestInterface; use Slim\Http\Response; require_once __DIR__ . '/vendor/autoload.php'; $app = new Slim\App(include __DIR__ . '/config/settings.php'); (new \App\Configurator())->loadDependencyDefaults($app->getContainer()); $app->getContainer()->get('logger'); // Get $app->get('/{resource}[/{id}]', function (ServerRequestInterface $request, Response $response, $resource, $id = null) { /** * @var ResponseDataFormatter $formatter */ $formatter = $this->get('dataFormatter'); try { $resource = AbstractResource::load($resource, $request, $response, $this); return $response->withJson($formatter->getSuccess($resource->get($id))); } catch (StatusException $e) { return $response->withJson($formatter->getFailure($e->getMessage()), $e->getCode()); } catch (Exception $e) { return $response->withStatus(500); } }); // Post $app->post('/{resource}', function (ServerRequestInterface $request, Response $response, $resource) { /** * @var ResponseDataFormatter $formatter */ $formatter = $this->get('dataFormatter'); try { $resource = AbstractResource::load($resource, $request, $response, $this); return $response->withJson($formatter->getSuccess($resource->post()));
<?php error_reporting(-1); require_once __DIR__ . '/vendor/autoload.php'; $app = new \Slim\App(); // Test 1: JSON serialization $app->get('/json', function ($request, $response) { return $response->withJson(array('message' => 'Hello, World!'))->withHeader('Content-Type', 'application/json'); }); $container = $app->getContainer(); $container['db'] = function ($c) { $db = $c['settings']['db']; $pdo = new PDO('mysql:host=localhost;dbname=hello_world', 'benchmarkdbuser', 'benchmarkdbpass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $pdo; }; // Test 2: Single database query $app->get('/db', function ($request, $response) { $sth = $this->db->prepare('SELECT * FROM World WHERE id = ?'); $sth->execute(array(mt_rand(1, 10000))); $world = $sth->fetch(); # Cast fields to int so they don't get wrapped with quotes $world['id'] = (int) $world['id']; $world['randomNumber'] = (int) $world['randomNumber']; return $response->withJson($world)->withHeader('Content-Type', 'application/json'); }); // Test 3: Multiple database queries $app->get('/dbs', function ($request, $response) { $queries = max(1, min($request->getParam('queries'), 500)); $sth = $this->db->prepare('SELECT * FROM World WHERE id = ?');
//Any stuff with a 'util' path is basically a refactored and //improved version of the same programme under the 'utilities' path require './vendor/autoload.php'; use jra\model\FileManager; use jra\factory\ImageFactory; //We need autoloading for these chaps include 'homeController.php'; $app = new \Slim\App(); $container = $app->getContainer(); $container['view'] = function ($container) { $view = new \Slim\Views\Twig('./templates'); $view->addExtension(new \Slim\Views\TwigExtension($container['router'], $container['request']->getUri())); return $view; }; $app->get('/', function ($request, $response, $args) { return $this->view->render($response, 'index.phtml'); })->setName('index'); $app->get('/util', "jra\\HomeController:dispatch"); $app->map(['GET', 'POST'], '/util/photodata', function ($request, $response, $args) { $path = './assets/images/photodata/'; $filename = $_FILES['file']['name']; $fileManager = new FileManager(); $fileManager->uploadFile($path . $filename); $imageFactory = new ImageFactory(); //Don't see why I need to call this again even though it's //called in the constructor? $imageFactory->populateImages(); return $this->view->render($response, 'photodata.phtml', ['title' => 'Exif Data Viewer', 'images' => $imageFactory->images, 'stylesheet' => '/assets/css/components/cards/card-1/card-1.css', 'sweetalertcss' => '/libraries/sweetalert/dist/sweetalert.css', 'sweetalertjs' => '/libraries/sweetalert/dist/sweetalert.min.js', 'script' => '/assets/js/photodata.js']); }); $app->map(['GET', 'POST'], '/util/rawtext', function ($request, $response, $args) { return $this->view->render($response, 'rawtext.phtml', ['title' => 'Raw Text', 'input' => json_encode($_POST['input'])]);
$body = $newresponse->getBody(); $body->write($output); } else { //login unsuccessful $newresponse = $newresponse->withStatus(401); } return $newresponse; }); //API function:GET:Get file list $app->get('/getfilelist/{token}/{user_id}', function (Request $request, Response $response, $args) use($app) { //set output header: content-type $newresponse = $response->withHeader('Content-type', 'application/json'); //check if token is expired or invalid if (!checktoken($args['user_id'], $args['token'])) { //request not authorised $newresponse = $newresponse->withStatus(401); //return $newresponse; return $newresponse; } $tmp = json_encode(scandirectory(".")); $newresponse->getBody()->write($tmp); return $newresponse; }); //API function:GET:Download specific file $app->get('/getfile/{id}/{token}/{user_id}', function (Request $request, Response $response, $args) use($app) { //set output header: content-type $newresponse = $response->withHeader('Content-type', 'application/json'); //check if token is expired or invalid if (!checktoken($args['user_id'], $args['token'])) { //request not authorised $newresponse = $newresponse->withStatus(401); //return $newresponse;
require_once 'Db/Db.php'; //require_once 'sendmail.php'; //require 'RedBeanPHP/rb.php'; // set up database connection //R::setup('mysql:host=' . $dbConfig['host'] . ';dbname=' . $dbConfig['name'], $dbConfig['user'], $dbConfig['pass']); //R::freeze(true); // ToDo: use this for compression - http://pieroxy.net/blog/pages/lz-string/index.html use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; $app = new \Slim\App(); $auth = new \Middleware\Authenticate(); global $app_config; $app_config = parse_ini_file('config.ini', true); $app->get('/version', function ($request, $response, $args) { $id = array('service' => 'Going Dutch API', 'version' => '0.1', 'uid' => \Middleware\Authenticate::$requestUid); $response->write(json_encode($id)); return $response; })->add($auth); $app->get('/groups', function ($request, $response, $args) { $member = new \Models\Member(); $response->write($member->getGroupsBalance(\Middleware\Authenticate::$requestUid)); $newResponse = $response->withHeader('Content-type', 'application/json'); return $newResponse; })->add($auth); $app->put('/groups', function ($request, $response, $args) { $member = new \Models\Group(); $response->write($member->updateGroupDetails($request->getParsedBody(), \Middleware\Authenticate::$requestUid)); $newResponse = $response->withHeader('Content-type', 'application/json'); return $newResponse; })->add($auth); $app->get('/users', function ($request, $response, $args) {
// Create Slim app $app = new \Slim\App(['settings' => ['debug' => true]]); // Add whoops to slim because its helps debuggin' and is pretty. $app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware()); // Fetch DI Container $container = $app->getContainer(); // Instantiate and add Slim specific extension $view = new \Slim\Views\Twig(__DIR__ . '/views', ['cache' => $container->get('settings')['debug'] ? false : __DIR__ . '/cache']); $view->addExtension(new Slim\Views\TwigExtension($container->get('router'), $container->get('request')->getUri())); // Register Twig View helper $container->register($view); // Write some default variables available to every template $view->offsetSet('realtime_url', $environment['REALTIME_URL']); $view->offsetSet('current_watts', is_numeric($redis->get('owlintuition.watts')) ? $redis->get('owlintuition.watts') : '???'); $app->get('/', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) { header("Location: /redis"); exit; }); $app->get('/redis', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) { global $redis; $keys = $redis->keys('*'); $redisKeys = []; foreach ($keys as $key) { $redisKeys[$key] = ['key' => $key, 'value' => $redis->get($key)]; } ksort($redisKeys); return $this->view->render($response, 'redis/view.html.twig', ['redisKeys' => array_values($redisKeys)]); })->setName('redis'); $app->get('/power', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) { $powerConsumptionRecords = \AE\Models\PowerConsumption::search()->order('created', 'DESC')->where("created", date("Y-m-d H:i:s", strtotime('1 month ago')), ">=")->exec(); $watts = array_map(create_function('$o', 'return $o->watts;'), $powerConsumptionRecords); return $this->view->render($response, 'power/view.html.twig', ['powerConsumptionRecords' => $powerConsumptionRecords, 'count_datapoints' => count($watts), 'average_watts' => number_format(array_sum($watts) / count($watts), 0)]);
$container = new \Slim\Container($configuration); // Create and configure Slim app $app = new \Slim\App($container); // oAuthMiddleware : check resource requests $oAuthMiddleware = function ($request, $response, $next) { if (!$this->server->verifyResourceRequest($this->server->getRequest())) { $this->server->getResponse()->send(); die; // Important, otherwise Slim overrides HTTP headers } $response = $next($request, $response); return $response; }; // Homepage $app->get('/', function ($request, $response, $args) { return $response->write("homepage"); }); // Token request $app->post('/token', function ($request, $response, $args) { // Handle a request for an OAuth2.0 Access Token and send the response to the client $this->server->handleTokenRequest($this->server->getRequest())->send(); die; // Important, otherwise Slim overrides HTTP headers }); // Sync request $app->post('/sync', function ($request, $response, $args) { $token = $this->server->getAccessTokenData($this->server->getRequest()); $deviceNotes = $this->db->getDeviceNotesFromJson($request->getParam('notes')); $devices = $this->db->getDevices($token['user_id']); $cloudNotes = $this->db->getNotesToSync($token['user_id'], $token['device_id']); $this->db->insertNotesFromDevice($deviceNotes);
<?php require_once __DIR__ . '/../vendor/autoload.php'; $container = new \Slim\Container(); $container['config'] = (require_once __DIR__ . '/../app/settings.php'); require_once __DIR__ . '/../app/dependencies.php'; $app = new \Slim\App($container); // Register middleware $app->add(new \Slim\HttpCache\Cache('public', $container['config']['cache_lifetime'])); $app->get('/', function ($request, $response) { $domain = $this->environment['HTTP_HOST']; try { $this->sites->load(); $target = $this->sites->lookup($domain); } catch (\Exception $e) { $target = (object) array('redirect' => $this->config['sites']['default_url']); } if (empty($target->status)) { $target->status = $this->config['sites']['default_status']; } $response = $response->withStatus($target->status)->withAddedHeader('Location', $target->redirect); return $response; }); $app->put('/update', function ($request, $response) { /* if ('HTTPS' != $request->getUri()->getScheme()) { return $response->withStatus(400); } */ $key = $this->config['shared_key']; $json = $request->getParsedBody(); if ($json->key != $key) {
$container = $app->getContainer(); $container['renderer'] = function ($c) { return new Slim\Views\PhpRenderer('site/templates/'); }; $container['docrender'] = function ($c) { return new Slim\Views\PhpRenderer('api/doc/'); }; require 'config.php'; require 'dependencies.php'; function getConnection() { global $server, $database, $user, $password; $dbh = new PDO("mysql:host={$server};dbname={$database}", $user, $password); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbh; } $app->group('/', function () use($app) { require 'site/routes/site.php'; }); $app->group('/api', function () use($app) { require 'api/routes/champions.php'; require 'api/routes/teams.php'; require 'api/routes/compos.php'; require 'api/routes/regions.php'; require 'api/routes/bans.php'; require 'api/routes/games.php'; $app->get('/doc/', function ($req, $res, $args) { return $this->docrender->render($res, 'index.html', $args); }); }); $app->run();
use Psr\Http\Message\ResponseInterface as Response; require 'vendor/autoload.php'; $app = new \Slim\App(); /* exemple de route slim $app->get('/', function (Request $request, Response $response) { $response->getBody()->write("{'nom':'Durand','age':'28'}"); return $response; });*/ $app->get('/api/wines', function (Request $request, Response $response) { try { $db = thisConnection(); $stmt = $db->query("SELECT* FROM wine ORDER BY name"); $wines = $stmt->fetchAll(PDO::FETCH_OBJ); $response->getBody()->write('{"vins": ' . json_encode($wines) . '}'); } catch (PDOException $e) { $response->getBody()->write('{"error":' . $e->getMessage() . '}'); die; } return $response; }); $app->get('/api/wines/{id}', function (Request $request, Response $response, $args) { try { $id = $args['id']; $db = thisConnection(); $stmt = $db->query("SELECT* FROM wine WHERE id=" . $id . " ORDER BY name"); $wines = $stmt->fetchAll(PDO::FETCH_OBJ); $response->getBody()->write('{"vinsId": ' . json_encode($wines) . '}'); } catch (PDOException $e) { $response->getBody()->write('{"error":' . $e->getMessage() . '}'); die;
require 'vendor/autoload.php'; $app = new \Slim\App(); $app->add(function (Request $request, Response $response, callable $next) { $uri = $request->getUri(); $path = $uri->getPath(); if ($path != '/' && substr($path, -1) == '/') { // permanently redirect paths with a trailing slash // to their non-trailing counterpart $uri = $uri->withPath(substr($path, 0, -1)); return $response->withRedirect((string) $uri, 301); } return $next($request, $response); }); $app->get('/api/stryktipset', function (Request $request, Response $response) { $response = $response->withHeader('Content-type', 'application/json'); require 'api/cStryktipsetApi.php'; $response->getBody()->write(StryktipsetApi::getRow()); return $response; }); $app->get('/api/matches', function (Request $request, Response $response) { $response = $response->withHeader('Content-type', 'application/json'); require 'api/cMatchesApi.php'; $response->getBody()->write(MatchesApi::getMatches()); return $response; }); $app->get('/api/matches/{team}', function (Request $request, Response $response, $args) { $response = $response->withHeader('Content-type', 'application/json'); require 'api/cMatchesApi.php'; $response->getBody()->write(MatchesApi::getTeam($args['team'])); return $response; }); $app->get('/', function (Request $request, Response $response) {
<?php use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; require 'vendor/autoload.php'; $app = new \Slim\App(); $app->get('/', function (Request $request, Response $response) { $response->getBody()->write("Page d'accueil"); return $response; }); $app->get('/hello/{name}', function (Request $request, Response $response) { $name = $request->getAttribute('name'); $response->getBody()->write("Hello, {$name}"); return $response; }); $app->run();
<html> <head> <?php include "require.php"; ?> </head> <body> <?php // Create and configure Slim app $app = new \Slim\App(); $app->get('/hello/:name' . function ($name) { echo "Hello {$name}"; }); $app->run(); ?> </body>
<?php require_once '../vendor/autoload.php'; $config = ['settings' => ['addContentLengthHeader' => false]]; $app = new \Slim\App($config); // Define app routes $app->get('/hello/{name}', function ($request, $response, $args) { return $response->write("Hello " . $args['name']); }); $app->get('/samplejson', function () { $json = (array) simplexml_load_file('http://shoggoth.net/?feed=rss2'); return json_encode($json); }); $app->get('/info', function () { phpinfo(); return null; }); $app->get('/', function () { return file_get_contents('../templates/index.html'); }); // Run app $app->run();
*/ $app = new Slim\App(); /** * Step 3: Getting connect with DB * * Here we define several Slim application routes that respond * to appropriate HTTP request methods. In this example, the second * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete` * is an anonymous function. */ $app->get('/db', function ($request, $response, $args) { try { $servername = '127.0.0.1'; // this may be an ip address instead $username = '******'; $password = ''; $conn = new PDO("mysql:host={$servername};dbname=test", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } }); /** * Step 4: Run the Slim application * * This method should be called last. This executes the Slim application * and returns the HTTP response to the HTTP client. */ $app->run();
/** * @author: Stanislav Fifik <*****@*****.**> */ namespace PhpScan; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; require '../vendor/autoload.php'; $app = new \Slim\App(); $config = parse_ini_file("../config.ini"); $sane = new Sane($config['device']); function validate($value, $valid_options) { foreach ($valid_options as $valid) { if ($value == $valid) { return $valid; } } throw new \HttpException("Invalid argument", 400); } $app->get('/preview', function (Request $request, Response $response) use($sane) { $params = $request->getQueryParams(); return $response->withRedirect(sprintf("../outputs/%s?%s", $sane->preview(array('--mode=' . validate($params['mode'], ['Lineart', 'Gray', 'Color']))), floor(time()))); }); $app->get('/scan', function (Request $request, Response $response) use($sane) { $filename = sprintf("Scan_%s.jpg", date("o-j-n_G:i:s")); $params = $request->getQueryParams(); return $response->withRedirect(sprintf("../outputs/%s?%s", $sane->scan($filename, array('--mode=' . validate($params['mode'], ['Lineart', 'Gray', 'Color']), '--resolution=' . validate($params['resolution'], [75, 150, 300, 600, 1200]))), floor(time()))); }); $app->run();
* Step 2: Instantiate a Slim application * * This example instantiates a Slim application using * its default settings. However, you will usually configure * your Slim application now by passing an associative array * of setting names and values into the application constructor. */ $app = new Slim\App(); /** * Step 3: Define the Slim application routes * * Here we define several Slim application routes that respond * to appropriate HTTP request methods. In this example, the second * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete` * is an anonymous function. */ $app->get('/', function ($request, $response, $args) { $response->write("Welcome to Slim!"); return $response; }); $app->get('/hello[/{name}]', function ($request, $response, $args) { $response->write("Hello, " . $args['name']); return $response; })->setArgument('name', 'World!'); /** * Step 4: Run the Slim application * * This method should be called last. This executes the Slim application * and returns the HTTP response to the HTTP client. */ $app->run();