/** * @dataProvider authenticationDataProvider */ public function testRouteAuthentication($requestMethod, $path, $location, $hasIdentity, $identity, $httpStatus) { \Slim\Environment::mock(array('REQUEST_METHOD' => $requestMethod, 'PATH_INFO' => $path)); $this->auth->expects($this->once())->method('hasIdentity')->will($this->returnValue($hasIdentity)); $this->auth->expects($this->once())->method('getIdentity')->will($this->returnValue($identity)); $app = new \Slim\Slim(array('debug' => false)); $app->error(function (\Exception $e) use($app) { // Example of handling Auth Exceptions if ($e instanceof AuthException) { $app->response->setStatus($e->getCode()); $app->response->setBody($e->getMessage()); } }); $app->get('/', function () { }); $app->get('/member', function () { }); $app->delete('/member/photo/:id', function ($id) { }); $app->get('/admin', function () { }); $app->map('/login', function () { })->via('GET', 'POST')->name('login'); $app->add($this->middleware); ob_start(); $app->run(); ob_end_clean(); $this->assertEquals($httpStatus, $app->response->status()); $this->assertEquals($location, $app->response->header('location')); }
/** * Create routes for all schemes based on behavior */ protected function _setupRoutes() { // default route for / $this->slim->get('/', array('One_Controller_Rest', 'defaultRouteHandler')); foreach (One_Repository::getSchemeNames() as $schemeName) { $scheme = One_Repository::getScheme($schemeName); if ($scheme->hasBehavior('restable')) { One_Behavior_Restable::slimSetup($this->slim, $scheme); } } }
public function testAdminNavigation() { \Slim\Environment::mock(array('SCRIPT_NAME' => '', 'PATH_INFO' => '/admin')); $app = new \Slim\Slim(); $app->view(new \Slim\View()); $app->get('/admin', function () { echo 'Success'; }); $auththenticationService = $this->getMock('Zend\\Authentication\\AuthenticationService'); $auththenticationService->expects($this->once())->method('hasIdentity')->will($this->returnValue(true)); $mw = new Navigation($auththenticationService); $mw->setApplication($app); $mw->setNextMiddleware($app); $mw->call(); $response = $app->response(); $navigation = $app->view()->getData('navigation'); $this->assertNotNull($navigation); $this->assertInternalType('array', $navigation); $this->assertEquals(4, count($navigation)); $this->assertEquals('Home', $navigation[0]['caption']); $this->assertEquals('/', $navigation[0]['href']); $this->assertEquals('', $navigation[0]['class']); $this->assertEquals('Admin', $navigation[1]['caption']); $this->assertEquals('/admin', $navigation[1]['href']); $this->assertEquals('active', $navigation[1]['class']); $this->assertEquals('Settings', $navigation[2]['caption']); $this->assertEquals('/admin/settings', $navigation[2]['href']); $this->assertEquals('', $navigation[2]['class']); $this->assertEquals('Logout', $navigation[3]['caption']); $this->assertEquals('/logout', $navigation[3]['href']); $this->assertEquals('', $navigation[3]['class']); }
private function runAppHead($action, $actionName, $mwOptions = NULL, $headers = array()) { \Slim\Environment::mock(array('REQUEST_METHOD' => 'HEAD', 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => 80, 'ACCEPT' => 'application/json', 'SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/' . $actionName)); $app = new \Slim\Slim(); $app->setName($actionName); $mw = function () { // Do nothing }; if (isset($mwOptions)) { if (is_callable($mwOptions)) { $mw = $mwOptions; } else { $mwOptions['appName'] = $actionName; $mw = \CorsSlim\CorsSlim::routeMiddleware($mwOptions); } } $app->get('/:name', $mw, function ($name) use($app, $action) { if ($app->request->isHead()) { $app->status(204); return; } $app->contentType('application/json'); $app->response->write(json_encode(array("action" => $action, "method" => "GET", "name" => $name))); }); foreach ($headers as $key => $value) { $app->request->headers()->set($key, $value); } $app->run(); $this->assertEquals(204, $app->response()->status()); return $app; }
/** * @param SlimWebServiceRegistryCategory $category */ public function AddCategory(SlimWebServiceRegistryCategory $category) { foreach ($category->Gets() as $registration) { $this->slim->get($registration->Route(), $registration->Callback())->name($registration->RouteName()); $this->SecureRegistration($registration); } foreach ($category->Posts() as $registration) { $this->slim->post($registration->Route(), $registration->Callback())->name($registration->RouteName()); $this->SecureRegistration($registration); } foreach ($category->Deletes() as $registration) { $this->slim->delete($registration->Route(), $registration->Callback())->name($registration->RouteName()); $this->SecureRegistration($registration); } $this->categories[] = $category; }
public function testBug2() { \Slim\Environment::mock(array("SCRIPT_NAME" => "/index.php", "PATH_INFO" => "/status/foo")); $app = new \Slim\Slim(); $app->get("/status/foo", function () { echo "Status"; }); $app->get("/status(/?)", function () { echo "Status"; }); $app->get("/stat", function () { echo "Stat"; }); $auth = new \Slim\Middleware\HttpBasicAuth(array("path" => "/stat", "realm" => "Protected", "users" => array("root" => "t00r", "user" => "passw0rd"))); $auth->setApplication($app); $auth->setNextMiddleware($app); $auth->call(); $this->assertEquals(200, $app->response()->status()); $this->assertEquals("Status", $app->response()->body()); }
/** * Test Language middleware with Accept-Language header */ public function testLanguageHeader() { \Slim\Environment::mock(array('HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8,es;q=0.6')); $app = new \Slim\Slim(array()); $app->get('/', function () { }); $mw = new \Mnlg\Middleware\Language(); $mw->setApplication($app); $mw->setNextMiddleware($app); $mw->call(); $this->assertEquals($app->acceptLanguages, array('en-US' => 1.0, 'en' => 0.8, 'es' => 0.6)); }
public function testVisitAdminPageLoggedInSucceeds() { \Slim\Environment::mock(array('SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/admin')); $app = new \Slim\Slim(); $app->get('/admin', function () { echo 'Success'; }); $this->auththenticationService->expects($this->once())->method('hasIdentity')->will($this->returnValue(true)); $this->middleware->setApplication($app); $this->middleware->setNextMiddleware($app); $this->middleware->call(); $response = $app->response(); $this->assertTrue($response->isOk()); }
public function testSetEditor() { \Slim\Environment::mock(array('SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/foo')); $app = new \Slim\Slim(); $app->config('whoops.editor', 'sublime'); $app->get('/foo', function () { echo "It is work"; }); $middleware = new WhoopsMiddleware(); $middleware->setApplication($app); $middleware->setNextMiddleware($app); $middleware->call(); $this->assertEquals('subl://open?url=file://test_path&line=168', $app->whoopsPrettyPageHandler->getEditorHref('test_path', 168)); }
/** * Test maintenance middleware when 'maintenance' mode is enabled with a custom callable */ public function testMaintenanceEnabledCustomCallable() { \Slim\Environment::mock(array('SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/')); $app = new \Slim\Slim(array('mode' => 'maintenance')); $app->get('/', function () { echo "Success"; }); $mw = new \Mnlg\Middleware\Maintenance(function () use($app) { $app->response()->body('Maintenance'); }); $mw->setApplication($app); $mw->setNextMiddleware($app); $mw->call(); $this->assertEquals(200, $app->response()->status()); $this->assertEquals('Maintenance', $app->response()->body()); }
public function testReturnsUnchangedSuccessResponse() { \Slim\Environment::mock(array('SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/simpletest')); $app = new \Slim\Slim(); $app->get('/simpletest', function () { echo 'Success'; }); $item = $this->getMockBuilder('\\Stash\\Item')->disableOriginalConstructor()->getMock(); $item->expects($this->any())->method('isMiss')->will($this->returnValue(true)); $pool = $this->getMockBuilder('\\Stash\\Pool')->disableOriginalConstructor()->getMock(); $pool->expects($this->any())->method('getItem')->will($this->returnValue($item)); $mw = new StashCache($pool); $mw->setApplication($app); $mw->setNextMiddleware($app); $mw->call(); $this->assertEquals(200, $app->response()->status()); $this->assertEquals('Success', $app->response()->body()); }
<?php require 'vendor/autoload.php'; require '../../lib/db.php'; require '../../lib/Classes/Config.php'; $slim = new \Slim\Slim(array('debug' => true, 'view' => new \Slim\Views\Twig())); $view = $slim->view(); $view->parserOptions = array('debug' => true); $view->parserExtensions = array(new \Slim\Views\TwigExtension()); /** Root URL */ $slim->get('/', function () use($slim) { $slim->response()->redirect('index.php/index'); }); /** The index page */ $slim->get('/index', function () use($slim) { $slim->render('index.php'); }); /** The enrolment page */ $slim->get('/enrol', function () use($slim) { // $slim->contentType('application/x-apple-aspen-config'); $config = get_config(); if (!isset($config)) { $config = array("access_rights" => 1024, "organisation_name" => "Abstractec", "master_profile_uuid" => "1234", "cert_uuid" => "4567", "mdm_uuid" => "7890", "mdm_certificate" => "certificate", "mdm_certificate_password" => "password", "mdm_topic" => "com.abstractec.mdm", "check_in_url" => "http://127.0.0.1:8888/~jimbob/service/checkin", "service_url" => "http://127.0.0.1:8888/~jimbob/service"); } $slim->response->headers->set('Content-Type', 'application/x-apple-aspen-config');
/** * Test custom error handler uses existing Response object */ public function testErrorHandlerUsesCurrentResponseObject() { $s = new \Slim\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 '../service/ContraMedidaService.php'; require_once '../model/ContraMedida.php'; require_once '../Slim/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $contraMedidaService = new ContraMedidaService(); $app->get("/", function () { echo "<h1>Hello World</h1>"; }); $app->get("/contraMedida/getall", function () use($app, $contraMedidaService) { echo '{"contraMedidas": ' . json_encode($contraMedidaService->buscarContraMedidas()) . '}'; }); $app->get("/contraMedida/:id", function ($id) use($app, $contraMedidaService) { echo json_encode($contraMedidaService->buscarContraMedida($id)); }); $app->post("/contraMedida/cadastrar", function () use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->cadastrarContraMedida($resultado->nomeContraMedida)); }); $app->put("/contraMedida/atualizar", function ($id) use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->atualizarContraMedida($resultado->idContraMedida, $resultado->nomeContramedida)); }); $app->delete("/contraMedida/remover/:id", function ($id) use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->removerContraMedida($id));
$app = new \Slim\Slim(); //$app -> get('/projects/:id', function($id){ $app->get('/projects/', function () { //set username $servername = "sql2.freemysqlhosting.net"; $username = "******"; $password = "******"; $dbname = "sql294036"; // create connection $conn = mysqli_connect($servername, $username, $password, $dbname); //check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM projects;"; $result = $conn->query($sql); $rows = mysqli_num_rows($result); $projects = new Projects(); $projects->projects = array(); while ($row = $result->fetch_array()) { $project1 = new Project(); $project1->id = $row["id"]; $project1->title = $row["title"]; $project1->image = $row["image"]; $project1->href = $row["href"]; array_push($projects->projects, $project1); } //echo json_encode($bproject1); echo json_encode($projects); }); $app->run();
$model = new \Model\App_Model($app->db); $authenticate = function ($app) { return function () use($app) { $app->hybridInstance; $session_identifier = Hybrid_Auth::storage()->get('user'); if (is_null($session_identifier) && $app->request()->getPathInfo() != '/login/') { $app->redirect('/login/'); } }; }; $app->get('/', function () use($app, $model) { $app->hybridInstance; $session_identifier = Hybrid_Auth::storage()->get('user'); $avatarUrl = $model->getAvatarUrl($session_identifier); if (isset($session_identifier) && !empty($session_identifier)) { $scriptID = 'i'; } else { $scriptID = '!i'; } $app->render('home.php', ['datajs' => 'home.js', 'datagroupjs' => '', 'name' => 'Home', 'avatarURL' => $avatarUrl, 'identifier' => $session_identifier, 'scriptID' => $scriptID]); })->name('home'); $app->get('/login/', $authenticate($app), function () use($app) { $app->render('login.php', ['datajs' => '', 'datagroupjs' => '', 'name' => 'Login']); }); $app->get('/login/:idp', function ($idp) use($app, $model) { try { $adapter = $app->hybridInstance->authenticate(ucwords($idp)); $user_profile = $adapter->getUserProfile(); if (empty($user_profile)) { $app->redirect('/login/?err=1'); }
require 'Slim/Slim.php'; require 'plugins/NotORM.php'; require 'plugins/Spyc.php'; include_once 'controllers/controller.php'; include_once 'controllers/alumnos.php'; include_once 'controllers/cursos.php'; $config = Spyc::YAMLLoad('config.yaml'); $dsn = $config["db"]["method"] . $config["db"]["name"] . ";charset=" . $config["db"]["charset"]; $pdo = new PDO($dsn, $config["db"]["user"], $config["db"]["pass"]); $db = new NotORM($pdo); /* Register autoloader and instantiate Slim */ \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); // Configuración de las rutas $app->get('/', function () { echo 'App BT'; }); $app->group('/cursos', function () use($app, $db) { $app->get('/', function () use($app, $db) { //devuelve todos los cursos $courseController = new \Controllers\Cursos($app, $db); $courseController->index(); }); $app->get('/:id', function ($id) use($app, $db) { //devuelve el curso según el id dado $courseController = new \Controllers\Cursos($app, $db); $courseController->view($id); }); $app->get('/:id/obtener_clase', function ($id) use($app, $db) { //status true: devuelve la clase más reciente según el id dado $courseController = new \Controllers\Cursos($app, $db);
if ($inner_command["Command"]["RequestType"] == "DeviceLock") { $request_dict->add('RequestType', new \CFPropertyList\CFString("DeviceLock")); } $dict->add("Command", $request_dict); $dict->add("CommandUUID", new \CFPropertyList\CFString($inner_command["CommandUUID"])); echo $res_plist->toXML(true); } else { // empty plist for you $res_plist = new \CFPropertyList\CFPropertyList(); $res_plist->add($dict = new \CFPropertyList\CFDictionary()); echo $res_plist->toXML(true); } } }); $slim->get('/checkin', function () use($slim) { //doCheckin($slim); }); $slim->put('/checkin', function () use($slim) { // read data, do things $body = $slim->request->getBody(); if (!isset($body) || strlen($body) == 0) { $slim->response()->status(401); // not authorised } else { $body = str_replace("#012", "", $body); $body = str_replace("#011", "", $body); syslog(LOG_DEBUG, "c"); syslog(LOG_DEBUG, $body); $plist = new \CFPropertyList\CFPropertyList(); $plist->parse($body); $message = $plist->toArray();
$app = new \Slim\Slim(array('view' => new \Slim\Views\Twig())); $view = $app->view(); $view->parserOptions = array('debug' => true, 'cache' => dirname(__FILE__) . '/cache'); $view->parserExtensions = array(new \Slim\Views\TwigExtension()); //dont ovveriden view /* $app = new \Slim\Slim(); */ //first example /* $app->get('/hello/:name', function ($name) { echo "Hello, $name"; }); */ $app->get('/', function () use($app) { $app->render('about.twig'); }); $app->get('/contact', function () use($app) { //DEBUG check it with name function $app->render('contact.twig'); }); $app->post('/contact', function () use($app) { $name = $app->request()->post('name'); $email = $app->request()->post('email'); $msg = $app->request()->post('msg'); if (!empty($name) && !empty($email) && !empty($msg)) { $claenName = filter_var($name, FILTER_SANITIZE_STRING); $claenEmail = filter_var($email, FILTER_SANITIZE_EMAIL); $claenMsg = filter_var($msg, FILTER_SANITIZE_STRING); } else { $app->redirect('contact');
* 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. */ // GET route $app->get('/', function () { $template = <<<EOT <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Slim Framework for PHP 5</title> </head> <body> <h1>Welcome to Slim!</h1> <p>Hello World!</p> <p>APIs include: fslist, crud, test</p> </body> </html> EOT; echo $template; $isJSON = 1; }); // POST route $app->post('/post', function () { // echo 'This is a POST route'; // Helpful reference: // http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/ // key change being need to use \Slim\Slim:: not just Slim::
<?php require __DIR__ . '/utility.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->notFound(function () use($dati, $app) { $app->render('shared/404.php', array('dati' => $dati)); }); $app->get('/', function () use($dati, $app) { $app->render('index.php', array('dati' => $dati)); })->name('index'); $app->map('/contattaci', function () use($dati, $app) { $app->render('email.php', array('dati' => $dati)); if (fatto()) { $app->redirect($app->urlFor('index')); } })->via('GET', 'POST'); $app->map('/templates(/:name+)', function ($name) use($dati, $app) { $app->render('shared/404.php', array('dati' => $dati)); })->via('GET', 'POST'); $app->get('/guida/:id', function ($id) use($dati, $app) { $app->render('index.php', array('dati' => $dati, 'guida' => $id)); }); $app->get('/logout', function () use($dati, $app) { $app->render('login/logout.php', array('dati' => $dati)); $app->redirect($app->urlFor('index')); }); if (!$dati['debug'] || isAdminUserAutenticate()) { $app->map('/login', function () use($dati, $app) { $app->render('login/index.php', array('dati' => $dati)); if (isUserAutenticate()) {
case "/api/getSupNRPEPlugin": case "/api/getRouterVM": case "/api/getNagiosPlugin": case "/api/getNagiosPlugins": require_once BASE_PATH . "/routes/apiv1.route.php"; break; default: break; } }); $app->contentType('application/json'); $app->notFound(function () use($app) { $request = $app->request(); $headers = $request->headers(); $uri = $request->getResourceUri(); $apiResponse = new APIViewData(1, false, "The page you are looking for could not be found. Check the address to ensure your URL is spelled correctly..."); $apiResponse->setExtraResponseData('url', $request->headers('X_FORWARDED_PROTO') . '://' . $request->headers('HOST') . $request->getRootUri() . $request->getResourceUri()); $app->halt('404', $apiResponse->returnJson()); }); // Initial Dummy Routes // Leave the / on the end of /sapi/ due to rewrite engine, otherwise requests to /sapi break $app->get('/sapi/', function () use($app) { $msg = "Welcome to /sapi/ ... What can we help you with?"; $apiResponse = new APIViewData(0, false, $msg); $apiResponse->printJson(); })->name('saigon-api'); $app->get('/sapi/version', function () use($app) { $apiResponse = new APIViewData(0, false, API_VERSION . " (alpha/beta/charlie/delta/echo/use at your own risk)"); $apiResponse->printJson(); })->name('saigon-api-version'); $app->run();
include 'ChromePhp.php'; require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../models/productMgr.php'; require_once __DIR__ . '/../models/blogMgr.php'; require_once __DIR__ . '/../models/mailer.php'; $oProductMgr = new ProductMgr(); $oBlogMgr = new BlogMgr(); $oApp = new \Slim\Slim(array('templates.path' => __DIR__ . '/../views')); date_default_timezone_set('Canada/Saskatchewan'); $oApp->add(new \Slim\Middleware\SessionCookie(array('expires' => '60 minutes', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'slim_session', 'secret' => 'CHANGE_ME', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC))); /*** * Home page ***/ $oApp->get('/', function () use($oApp, $oProductMgr) { $oApp->render('home.phtml', array('title' => '', 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => 'Action', 'productsInGenre' => $oProductMgr->getProductsByGenre('Action'), 'featuredProducts' => $oProductMgr->getFeaturedProducts())); }); $oApp->get('/home/:genre', function ($sGenre) use($oApp, $oProductMgr) { $oApp->render('home.phtml', array('title' => $sGenre, 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => $sGenre, 'productsInGenre' => $oProductMgr->getProductsByGenre($sGenre), 'featuredProducts' => $oProductMgr->getFeaturedProducts())); }); // called when user search for items $oApp->post('/search', function () use($oApp, $oProductMgr) { $sKeywords = $oApp->request()->post('keywords'); $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords)); }); $oApp->get('/search', function () use($oApp, $oProductMgr) { $sKeywords = $oApp->request->params('keywords'); //ChromePhp::info($sKeywords); //die(); $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords)); });
// Lo haremos utilizando PDO con el driver mysql. define('BD_SERVIDOR', 'localhost'); define('BD_NOMBRE', 'cellar'); define('BD_USUARIO', 'root'); define('BD_PASSWORD', ''); // Hacemos la conexión a la base de datos con PDO. // Para activar las collations en UTF8 podemos hacerlo al crear la conexión por PDO // o bien una vez hecha la conexión con // $db->exec("set names utf8"); $db = new PDO('mysql:host=' . BD_SERVIDOR . ';dbname=' . BD_NOMBRE . ';charset=utf8', BD_USUARIO, BD_PASSWORD); //////////////////////////////////////////// // Definición de rutas en la aplicación: // Ruta por defecto de la aplicación / //////////////////////////////////////////// $app->get('/', function () { echo "Pagina de gestión API REST de mi aplicación."; }); // Cuando accedamos por get a la ruta /usuarios ejecutará lo siguiente: $app->get('/usuarios', function () use($db) { // Si necesitamos acceder a alguna variable global en el framework // Tenemos que pasarla con use() en la cabecera de la función. Ejemplo: use($db) // Va a devolver un objeto JSON con los datos de usuarios. // Preparamos la consulta a la tabla. echo "Lista de usuarios"; $consulta = $db->prepare("select * from soporte_usuarios"); $consulta->execute(); // Almacenamos los resultados en un array asociativo. $resultados = $consulta->fetchAll(PDO::FETCH_ASSOC); // Devolvemos ese array asociativo como un string JSON. echo json_encode($resultados); });
**********************************************************************************/ $app = new \Slim\Slim(); /********************************************************************************** * 2. definir las rutas: ***********************************************************************************/ /* * Ruta para mostrar el menú de categorías */ $app->get('/categorias', function () { $mongo = new MongoClient(); // conectamos con la BD $database = $mongo->plazamar; // seleccionamos la BD $collection = $database->categorias; // seleccionamos la colección de datos (categorias) $cursor = $collection->find()->sort(array("nombre" => 1)); // indicamos que queremos recorrer todas las entradas y ordenarlas por nombre // retornamos los valores de la colección $data = []; foreach ($cursor as $categoria) { array_push($data, $categoria); } echo json_encode($data); }); /* * Ruta para mostrar los productos en la portada de la aplicación */ $app->get('/productosInicio', function () { $mongo = new MongoClient(); $database = $mongo->plazamar; $collection = $database->productos; $datos = [];
error_reporting(E_ALL); require 'Slim/Slim.php'; require 'utils/ManagerDB.php'; require 'utils/ParserCSV.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->get( '/hello/:name', function ($name) { // echo "Hello ".$name; $managerDB = new ManagerDB(); $managerDB->debugManagerDB(); } ); $app->post( '/users', function () use($app) { $paramEmail = $app->request->post('email'); $paramPassword = $app->request->post('password'); $paramPasswordConfirm = $app->request->post('password_confirmation'); $paramLogin = $app->request->post('login');
Description: Core de API RestFUL para consulta de saldo de tarjeta Bip! Version: 1 Author: Francisco Capone Author Mail: francisco.capone@gmail.com Author URI: http://www.franciscocapone.com */ @session_start(); require_once 'class/Utils.class.php'; require_once 'class/AbstractCURL.class.php'; require_once 'class/Bip.class.php'; require_once 'class/vendor/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $restBipApp = new \Slim\Slim(); $restBipApp->config(array('templates.path' => 'vistas')); $restBipApp->get('/', function () use($restBipApp) { $restBipApp->response->setStatus(200); echo "RestFUL BIP!"; }); $restBipApp->contentType('text/html; charset=utf-8'); $restBipApp->get('/getSaldo/:id', function ($id) { $restBipApp = \Slim\Slim::getInstance(); try { $resultadosSaldo = new Bip($id); if ($resultadosSaldo) { $restBipApp->response->setStatus(200); $restBipApp->response()->headers->set('Access-Control-Allow-Origin', '*'); $restBipApp->response()->headers->set('Content-Type', 'application/json'); print_r($resultadosSaldo->getData()); } } catch (Exception $e) { $restBipApp->response()->setStatus(404); echo '{"error":{"text":' . $e->getMessage() . '}}';
// Indicamos el tipo de contenido y condificación que devolvemos desde el framework Slim. #$app->contentType('text/html; charset=utf-8'); // Definimos conexion de la base de datos. // Lo haremos utilizando PDO con el driver mysql. define('BD_SERVIDOR', 'localhost'); define('BD_NOMBRE', 'soporte_usuarios'); define('BD_USUARIO', 'root'); define('BD_PASSWORD', ''); // Hacemos la conexión a la base de datos con PDO. // Para activar las collations en UTF8 podemos hacerlo al crear la conexión por PDO // o bien una vez hecha la conexión con // $db->exec("set names utf8"); $db = new PDO('mysql:host=' . BD_SERVIDOR . ';dbname=' . BD_NOMBRE . ';charset=utf8', BD_USUARIO, BD_PASSWORD); //$db->exec("set names utf8"); $app->get('/', function () { echo "Pagina de gestión API REST de mi aplicación."; }); // Cuando accedamos por get a la ruta /usuarios ejecutará lo siguiente: $app->get('/usuarios', function () use($db) { // Si necesitamos acceder a alguna variable global en el framework // Tenemos que pasarla con use() en la cabecera de la función. Ejemplo: use($db) // Va a devolver un objeto JSON con los datos de usuarios. // Preparamos la consulta a la tabla. $consulta = $db->prepare("select * from usuarios"); $consulta->execute(); // Almacenamos los resultados en un array asociativo. $resultados = $consulta->fetchAll(PDO::FETCH_ASSOC); // Devolvemos ese array asociativo como un string JSON. echo json_encode($resultados); }); // Accedemos por get a /usuarios/ pasando un id de usuario.
$app = new \Slim\Slim(); //------------------------------------------------------------------------ //------------------------------------------------------------------------ //------------------------------------------------------------------------ $app->get('/getShopByUserId', function () use($app) { $db = getDB(); $user = json_decode($app->request->getBody(), true); $shop = array(); $stt = "SELECT tblShop.id, tblShop.transactionValue, "; $stt = $stt . " tblCart.gameIdFk, tblGame.name, tblGame.console, "; $stt = $stt . " tblGame.photoLink, tblCart.transactionValue as gameValue "; $stt = $stt . " FROM tblShop "; $stt = $stt . " INNER JOIN tblShopCart ON tblShopCart.id = tblCart.shopIdFk "; $stt = $stt . " INNER JOIN tblCart ON tblCart.id = tblShopCart.cartIdFk "; $stt = $stt . " INNER JOIN tblGame ON tblGame.id = tblCart.gameIdFk "; $stt = $stt . " WHERE tblShop.userIdFk = " . $user['id'] . " ; "; $result = mysql_query($stt, $db); if ($result) { while ($row = mysql_fetch_array($result)) { $shop[] = array('id' => $row['id'], 'transactionValue' => $row['transactionValue'], 'gameIdFk' => $row['gameIdFk'], 'name' => $row['name'], 'console' => $row['console'], 'photoLink' => $row['photoLink'], 'gameValue' => $row['gameValue']); } } else { echo 'FAIL'; } $app->response()->header('Content_type', 'application/json'); echo json_encode($shop); }); //------------------------------------------------------------------------ //------------------------------------------------------------------------ //------------------------------------------------------------------------ $app->run();
<?php require 'vendor/autoload.php'; require 'classes/indeed.php'; error_reporting(-1); //tell me stuff $app = new \Slim\Slim(); $app->get('/home', function () { }); //so far nothing for home $app->get('/selection/:job', function ($job) { $client = new Indeed("4779755742469402"); $params = array("q" => $job, "l" => $location, "userip" => $_SERVER['REMOTE_ADDR'], "useragent" => $_SERVER['HTTP_USER_AGENT'], "limit" => "25"); $results = $client->search($params); echo json_encode($results); }); $app->get('/selection/:job/:location', function ($job, $location) { $client = new Indeed("4779755742469402"); $params = array("q" => $job, "l" => $location, "userip" => $_SERVER['REMOTE_ADDR'], "useragent" => $_SERVER['HTTP_USER_AGENT'], "limit" => "25"); $results = $client->search($params); echo json_encode($results); }); $app->get('/selection/:job/:location/:page', function ($job, $location, $page) { $client = new Indeed("4779755742469402"); $params = array("q" => $job, "l" => $location, "start" => $page * 25, "userip" => $_SERVER['REMOTE_ADDR'], "useragent" => $_SERVER['HTTP_USER_AGENT'], "limit" => "25"); $results = $client->search($params); echo json_encode($results); }); $app->post('/contact', function () { //send message in content $message = $_POST['name'];