public function enable(Slim $app) { $this->app = $app; $this->config = $this->app->config('api'); $this->factory = new Factory($this->config['resources']); // Middleware $this->app->add(new Database()); $this->app->add(new ApiMiddleware($this->config)); // Routes $this->app->get($this->config['prefix'] . '/:resource/:id', [$this, 'getAction'])->conditions(['id' => '\\d+'])->name('resource_get'); $this->app->get($this->config['prefix'] . '/:resource', [$this, 'listAction'])->name('resource_get_list'); $this->app->put($this->config['prefix'] . '/:resource/:id', [$this, 'putAction'])->conditions(['id' => '\\d+'])->name('resource_put'); $this->app->post($this->config['prefix'] . '/:resource', [$this, 'postAction'])->name('resource_post'); $this->app->delete($this->config['prefix'] . '/:resource/:id', [$this, 'deleteAction'])->conditions(['id' => '\\d+'])->name('resource_delete'); }
public static function slimSetup(\Slim\Slim &$slim, One_Scheme $scheme) { //TODO: read specs from behaviour options or from a file $opt = $scheme->get('behaviorOptions.restable'); $route = $opt['route']; // retrieve $slim->get("/{$route}", function () use($scheme) { One_Controller_Rest::restGetAll($scheme); }); // retrieve one $slim->get("/{$route}/:idOrAlias", function ($idOrAlias) use($scheme) { One_Controller_Rest::restGet($scheme, $idOrAlias); }); // create new $slim->post("/{$route}", function () use($scheme) { One_Controller_Rest::restPost($scheme); }); // update existing $slim->put("/{$route}/:idOrAlias", function ($idOrAlias) use($scheme) { One_Controller_Rest::restPut($scheme, $idOrAlias); }); // delete existing $slim->delete("/{$route}/:idOrAlias", function ($idOrAlias) use($scheme) { One_Controller_Rest::restDelete($scheme, $idOrAlias); }); }
function put($pattern, $controller, $method, $filter = null) { if (!is_callable($filter)) { $filter = function () { }; } return parent::put($pattern, $filter, function () use($controller, $method) { $instance = new $controller(); $args = func_get_args(); call_user_func_array(array($instance, $method), $args); }); }
private function addRoutesFromMeta(Slim $application, ClassMetadata $meta, Controller $controller) { $entitiesRoute = $this->getEntitiesRoute($meta); // Fetch entities route $application->get($entitiesRoute, function () use($meta, $controller) { $controller->getEntities($meta); }); // Create entity $application->post($entitiesRoute, function () use($meta, $controller) { $controller->createEntity($meta); }); $entityRoute = $this->getEntityRoute($meta, $entitiesRoute); // Get entity $application->get($entityRoute, function () use($meta, $controller) { $controller->getEntity($meta, func_get_args()); }); // Update entity $application->put($entityRoute, function () use($meta, $controller) { $controller->updateEntity($meta, func_get_args()); }); // Patch entity $application->patch($entityRoute, function () use($meta, $controller) { $controller->patchEntity($meta, func_get_args()); }); // Delete entity $application->delete($entityRoute, function () use($meta, $controller) { $controller->deleteEntity($meta, func_get_args()); }); // Handling associated entities foreach ($meta->getAssociationMappings() as $aName => $aData) { $aTargetClass = $meta->getAssociationTargetClass($aName); $aMeta = $this->getEntityMeta($aTargetClass); $aEntitiesRoute = $entityRoute . '/' . $aName; // Create associated entity // allow to create entity and link source together // POST /articles/1/tags will fetch article 1, create tag entity and // associate it to article 1 $application->post($aEntitiesRoute, function () use($meta, $aMeta, $controller, $aData) { $controller->createEntity($aMeta, $aData['fieldName'], $meta, func_get_args()); }); // List associated entities $application->get($aEntitiesRoute, function () use($meta, $controller, $aData) { $controller->getAssociatedEntities($aData['fieldName'], $meta, func_get_args()); }); // Associate two entities // POST /articles/1/tags/2 will associate article 1 to tag 2 $aEntityRoute = $this->getEntityRoute($aMeta, $aEntitiesRoute); $application->post($aEntityRoute, function () use($meta, $aMeta, $controller, $aData) { $controller->associateEntities($aMeta, $aData['fieldName'], $meta, func_get_args()); }); } return $application; }
private function _initRoutes() { $this->_slim->contentType('application/json'); $this->_slim->get('/basket/', array($this, 'getBaskets')); $this->_slim->get('/product/', array($this, 'getProducts')); $this->_slim->get('/basket/:id', array($this, 'getBasket')); $this->_slim->get('/basket/:id/item/', array($this, 'getBasketItems')); $this->_slim->get('/basket/:id/item/:prodId', array($this, 'getBasketItem')); $this->_slim->post('/basket/:id/item/', array($this, 'postBasketItem')); $this->_slim->put('/basket/:id/item/:prodId', array($this, 'putBasketItem')); $this->_slim->delete('/basket/:id/item/:prodId', array($this, 'deleteBasketItem')); }
$news = new news(); $news->worker('new_post', $data); }); $app->get('/news/:id', function ($id) { require '../news/news.worker.php'; $news = new news(); $news->worker('get_post', $id); }); $app->get('/news/edit/:id', function ($id) { require '../news/news.worker.php'; $news = new news(); $news->worker('edit_post', $id); }); $app->put('/news/edit/:id', function () { require '../news/news.worker.php'; $data = json_decode(Slim::getInstance()->request()->getBody(), true); $news = new news(); $news->worker('save_edit', $data); }); $app->delete('/news/:id', function ($id) { require '../news/news.worker.php'; $news = new news(); $news->worker('delete_post', $id); }); $app->get('/featured', function () { require '../news/news.worker.php'; $news = new news(); $news->worker('featured'); }); // ////////////////////////////// // Forum // Get Categories
<?php /* Author - Diego Alejandro Ramirez Contact - darasat@gmail.com */ require 'Slim/Slim.php'; use Slim\Slim; Slim::registerAutoloader(); $app = new Slim(); $app->get('/session', 'getSession'); $app->get('/getPhotos', 'getPhotos'); $app->get('/getPhoto/:id', 'getPhoto'); $app->post('/addPhoto', 'addPhoto'); $app->put('/updatePhoto/:id', 'updatePhoto'); $app->delete('/deletePhoto/:id', 'deletePhoto'); $app->run(); // Get Database Connection function getSession() { $db = new DB_Connection(); } function DB_Connection() { $dbhost = "127.0.0.1"; $dbuser = "******"; $dbpass = ""; $dbname = "ino"; $dbh = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbh;
*/ $app->get('/', function () use($emojiController) { //echo "Welcome to SweetEmoji"; $emojiController->all(); }); /* | "/emojis" get all emoji from the database */ $app->get('/emojis', function () use($emojiController) { $emojiController->all(); }); /* | "/emojis" create new emoji */ $app->put('/emojis', $authenticated, function () use($emojiController) { $emojiController->addEmoji(); }); /* | "/emojis" update emoji */ $app->patch('/emojis/:id', $authenticated, function ($id) use($emojiController) { $emojiController->updateEmoji($id); }); /* | "/emojis" find an emoji by id | POST method */ $app->get('/emojis/:id', function ($id) use($emojiController) { $emojiController->findEmoji($id); }); /*
$.get('service.php/links', function (x) { alert('Antwort = \n' + x); }) })(); */ $app->get('/', 'index'); //Alle Links abfragen $app->get('/links', 'getLinks'); //Ein Link abfragen mit Id $app->get('/links/:id', 'getLinks'); //Links durchsuchen $app->get('/links/search/:query', 'findByName'); //Link einfügen $app->post('/links', 'addLink'); //Link ändern $app->put('/links/:id', 'updateLink'); //Link löschen $app->post('/linkss/:id', 'deleteLink'); //deklaration für Anfrage mit Methode OPTIONS $app->run(); function index() { echo 'auf der Index Seite'; } function getLinks($id = null) { if (!$id) { echo 'jjj'; } else { echo $id; }
<?php require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); use Slim\Slim; $app = new Slim(array('debug' => true)); $app->get('/equipments', 'readEquipments'); $app->get('/equipments/:id', 'readEquipment'); $app->post('/equipments', 'createEquipment'); $app->put('/equipments/:id', 'updateEquipment'); $app->delete('/equipments/:id', 'deleteEquipment'); $app->get('/peoples', 'readPeople'); $app->get('/peoples/:id', 'readPerson'); $app->post('/peoples', 'createPerson'); $app->put('/peoples/:id', 'updatePerson'); $app->delete('/peoples/:id', 'deletePerson'); $app->run(); $mongoHost = 'localhost'; function readEquipments() { try { global $mongoHost; $connection = new MongoClient($mongoHost); $db = $connection->Equipments; $collection = $db->equipments; $cursor = $collection->find(); $equipments = []; foreach ($cursor as $obj) { array_push($equipments, $obj); } echo json_encode($equipments);
<?php namespace Oda; require '../../../../../../header.php'; require '../../../../../../vendor/autoload.php'; require '../../../../../../config/config.php'; use cebe\markdown\GithubMarkdown; use Slim\Slim; use stdClass, Oda\SimpleObject\OdaPrepareInterface, Oda\SimpleObject\OdaPrepareReqSql, Oda\OdaLibBd, Oda\InterfaceRest\UserInterface; $slim = new Slim(); //-------------------------------------------------------------------------- $slim->notFound(function () { $params = new OdaPrepareInterface(); $INTERFACE = new OdaRestInterface($params); $INTERFACE->dieInError('not found'); }); $slim->get('/', function () { $markdown = file_get_contents('./doc.markdown', true); $parser = new GithubMarkdown(); echo $parser->parse($markdown); }); //----------- USER ------------------------------- $slim->put('/user/pwd/', function () use($slim) { $params = new OdaPrepareInterface(); $params->slim = $slim; $params->arrayInput = array("userCode", "pwd", "email"); $INTERFACE = new UserInterface($params); $INTERFACE->resetPwd(); }); $slim->run();
ini_set('display_errors', 1); error_reporting(E_ALL); } date_default_timezone_set("UTC"); // registra Slim::registerAutoloader(); // inicializa e configura as rotas $app = new Slim(array('mode' => ENVIRONMENT == ENVIRONMENT_PROD ? 'production' : 'development')); if (CROSS_ORIGIN_ENABLED) { $app->response()->header('Access-Control-Allow-Origin', ACCESS_CONTROL_ALLOW_ORIGIN); } $app->get('/users/:userId/devices', 'authorize', 'getUserDevices'); $app->get('/users', 'authorize', 'getUsers'); $app->get('/devices', 'authorize', 'getDevices'); $app->post('/devices', 'authorize', 'createDevice'); $app->put('/devices', 'authorize', 'updateDevice'); $app->delete('/devices', 'authorize', 'deleteDevice'); $app->post('/notifications', 'authorize', 'sendNotification'); $app->run(); /** * Busca usuários que possuem dispositivos cadastrados * * Permite paginação através do parâmetros: * - page: página a ser retornada * - limit: quantidade de resultados a serem retornados */ function getUsers() { global $log; $app = Slim::getInstance(); try {
}); $app->get('/contacts/:id', $contentNegotiation, function ($id) use($app) { //This value should be specific to the current resource $lastModifiedTime = gmdate('D, d M Y H:i:s ') . ' GMT'; $app->response()->header('Last-Modified', $lastModifiedTime); $app->status(200); echo $app->render($app->template, ['contact' => ['contact_id' => $id, 'name' => $app->faker->firstName, 'last_name' => $app->faker->lastName]]); }); $app->put('/contacts/:id', $contentNegotiation, function ($id) use($app) { $contactInformation = $app->request()->getBody(); parse_str($contactInformation, $contact); $contact['contact_id'] = $id; if (empty($contact['name'])) { $contact['name'] = $app->faker->firstName; } if (empty($contact['last_name'])) { $contact['last_name'] = $app->faker->lastName; } $lastModifiedTime = time(); $app->lastModified($lastModifiedTime); $app->status(200); echo $app->render($app->template, ['contact' => $contact]); }); $app->delete('/contacts/:id', function ($id) use($app) { //Delete contact here $app->status(204); }); $app->options('/contacts/:id', function ($id) use($app) { $validOptions = ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']; $app->response()->header('Allow', implode(',', $validOptions)); });
// Route to accept the signup form $app->get('/login', 'getlogin'); $app->post('/login', 'validateLogin'); // Route to accept the login form $app->get('/error', 'error'); // Show Errors $app->get('/logout', 'logout'); // Logout // Backend // User section routes // user Dashboard $app->get('/dashboard/user/:id', 'showAccount'); // Show the account information $app->get('/dashboard/user_details/:id', 'showDetails'); // Show user Details $app->put('/dashboard/update/:id', 'updateDetails'); // Update user Details $app->put('/dashboard/account_type/:id', 'updateAccountType'); // Update user Details $app->put('/dashboard/account_pass/:id', 'updateAccountPass'); // Update user Details $app->delete('/dashboard/update/:id', 'deleteDetails'); // Delete user Details $app->get('/dashboard/user_deposit/:id', 'deposit'); // Show the Deposit Page $app->put('/dashboard/deposit/:id', 'updateDeposit'); // Route to accept the Deposit form $app->get('/dashboard/user_withdrawal/:id', 'withdrawal'); // Show the Withdrawal Page $app->put('/dashboard/withdrawal/:id', 'updateWithdrawal'); // Route to accept the Withdrawal form
} }); // Post $app->post('/:resource(/(:action)(/))', function ($resource, $subResource = null) use($app) { $resource = Resource::load($app->version, $resource, $subResource); if ($resource === null) { Resource::error(Resource::STATUS_NOT_FOUND, 'Cannot find requested resource.'); } else { $resource->post(); } }); // Put $app->put('/:resource(/(:action)(/))', function ($resource, $subResource = null) use($app) { $resource = Resource::load($app->version, $resource, $subResource); if ($resource === null) { Resource::error(Resource::STATUS_NOT_FOUND, 'Cannot find requested resource.'); } else { $resource->put(); } }); // Delete $app->delete('/:resource(/(:action)(/))', function ($resource, $subResource = null) use($app) { $resource = Resource::load($app->version, $resource, $subResource); if ($resource === null) { Resource::error(Resource::STATUS_NOT_FOUND, 'Cannot find requested resource.'); } else { $resource->delete(); } }); // Options $app->options('/:resource(/(:action)(/))', function ($resource, $subResource = null) use($app) { $resource = Resource::load($app->version, $resource, $subResource);
$app->post('/auth/login', function () use($authController) { $authController->login(); }); $app->get('/auth/logout', $authenticated, function () use($authController) { $authController->logout(); }); $app->get('/emojis', function () use($emojiController) { $emojiController->getAll(); }); $app->post('/emojis', function () use($emojiController) { $emojiController->addEmoji(); }); $app->get('/emojis/:id', function ($id) use($emojiController) { $emojiController->findEmoji($id); }); $app->post('/emojis/:id', function ($id) use($emojiController) { $emojiController->updateEmoji($id); }); $app->patch('/emojis/:id', function ($id) use($emojiController) { $emojiController->updateEmoji($id); }); $app->put('/emojis/:id', function ($id) use($emojiController) { $emojiController->updateEmoji($id); }); $app->delete('/emoji/:id', $authenticated, function ($id) use($emojiController) { $emojiController->deleteEmoji($id); }); $app->get('/', function () { echo "Welcome to Naija Emoji Service"; }); $app->run();
<?php require 'vendor/autoload.php'; use Slim\Slim; $app = new Slim(); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X GET http://localhost/comphppuebla/guzzle/contacts/1 $app->get('/contacts/:id', function ($id) { echo "Request via GET with ID = {$id}"; }); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X POST http://localhost/comphppuebla/guzzle/contacts $app->post('/contacts', function () { echo "Request via POST"; }); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X PUT http://localhost/comphppuebla/guzzle/contacts/2 $app->put('/contacts/:id', function ($id) { echo "Request via PUT with ID = {$id}"; }); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X DELETE http://localhost/comphppuebla/guzzle/contacts/3 $app->delete('/contacts/:id', function ($id) { echo "Request via DELETE with ID = {$id}"; }); // Replace /comphppuebla/guzzle for the path to your http-verbs.php file to try this route. // curl -X OPTIONS http://localhost/comphppuebla/guzzle/contacts/4 $app->options('/contacts/:id', function ($id) { echo "Request via OPTIONS with ID = {$id}"; }); $app->run();
/** * Create a Slim WebServices Application * * @param string $appName Application Name * @param string $key V3ctor WareHouse Key */ public function __construct($appName, $key) { $this->_key = $key; $this->_app = $appName; // Load Slim Application \Slim\Slim::registerAutoloader(); // Init Slim Application $this->web = new \Slim\Slim(); // Run WebServices Application $v3ctor = V3WareHouse::getInstance(); if (!$v3ctor->isConnected()) { $msg = array("error" => 'Unable load V3ctor WareHouse'); die(json_encode($msg)); } // Add Default Routes // Welcome $this->web->get('/', function () { $app = \Slim\Slim::getInstance(); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); $msg = array("msg" => 'Welcome to V3ctor WareHouse Application ' . $this->_app); echo json_encode($msg); }); // Gets Object by _id $this->web->get('/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); echo json_encode($v3ctor->findObject($entity, $id)); }); // Sets a New Object $this->web->post('/(:entity)', function ($entity) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); try { $body = $app->request->getBody(); $jsonData = json_decode($body); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); echo json_encode($v3ctor->newObject($entity, $jsonData)); } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } }); // Update a Object $this->web->put('/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); try { $body = $app->request->getBody(); $jsonData = json_decode($body); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); $result = $v3ctor->updateObject($entity, $id, $jsonData); $msgOk = array('msg' => 'OK'); $msgBad = array('msg' => 'ERROR'); if ($result) { echo json_encode($msgOk); } else { echo json_encode($msgBad); } } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } }); // Delete a Object $this->web->delete('/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); $result = $v3ctor->deleteObject($entity, $id); $msgOk = array('msg' => 'OK'); $msgBad = array('msg' => 'ERROR'); if ($result) { echo json_encode($msgOk); } else { echo json_encode($msgBad); } }); // Find Objects by Query $this->web->post('/query/(:entity)', function ($entity) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); try { $body = $app->request->getBody(); $jsonQuery = json_decode($body); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); $jsonQuery = (array) $jsonQuery; echo json_encode($v3ctor->query($entity, $jsonQuery)); } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } }); // Not Sent Key $this->web->get('/notkey', function () { $app = \Slim\Slim::getInstance(); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(404); $msg = array("error" => "Not Sent Key"); echo json_encode($msg); }); // Not Valid Key $this->web->get('/invalidkey', function () { $app = \Slim\Slim::getInstance(); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(404); $msg = array("error" => "Permission denied"); echo json_encode($msg); }); /************************* JSONP *************************/ // Gets Object by _id $this->web->get('/jsonp/get/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $jsonResult = json_encode($v3ctor->findObject($entity, $id)); echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); // Find Objects by Query $this->web->get('/jsonp/query/(:entity)', function ($entity) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $jsonData = $app->request()->get('data'); $jsonData = json_decode($jsonData); $jsonResult = json_encode($v3ctor->query($entity, $jsonData)); echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); // Sets a New Object $this->web->get('/jsonp/new/(:entity)', function ($entity) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $jsonData = $app->request()->get('data'); $jsonData = json_decode($jsonData); $jsonResult = json_encode($v3ctor->newObject($entity, $jsonData)); echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); // Update a Object $this->web->get('/jsonp/upd/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $jsonData = $app->request()->get('data'); $jsonData = json_decode($jsonData); $msgOk = array('msg' => 'OK'); $msgBad = array('msg' => 'ERROR'); $result = $v3ctor->updateObject($entity, $id, $jsonData); if ($result) { $jsonResult = json_encode($msgOk); } else { $jsonResult = json_encode($msgBad); } echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); // Delete a Object $this->web->get('/jsonp/del/(:entity)/(:id)', function ($entity, $id) { $app = \Slim\Slim::getInstance(); $v3ctor = V3WareHouse::getInstance(); $this->validateKey($app); $callback = $app->request()->get('callback'); if (is_null($callback)) { $app->response()->status(400); } else { try { $app->response()->header('Content-type: text/javascript'); $app->response()->status(200); $msgOk = array('msg' => 'OK'); $msgBad = array('msg' => 'ERROR'); $result = $v3ctor->deleteObject($entity, $id); if ($result) { $jsonResult = json_encode($msgOk); } else { $jsonResult = json_encode($msgBad); } echo "{$callback}(" . $jsonResult . ");"; } catch (ResourceNotFoundException $e) { $app->response()->status(404); } catch (Exception $e) { $app->response()->status(400); $app->response()->header('X-Status-Reason', $e->getMessage()); } } }); }
private function loadMethodAnnotations(Slim $app, \ReflectionMethod $method, $newInstanceClass, $uri) { $methodAnnotations = $this->getMethodAnnotations($method); $uriMethod = ''; if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\Path'])) { $uriMethod = $methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\Path']->uri; } $uri = $this->normalizeURI($uri, $uriMethod); if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\POST'])) { $app->post($uri, $method->invoke($newInstanceClass)); } if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\GET'])) { $app->get($uri, $method->invoke($newInstanceClass)); } if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\DELETE'])) { $app->delete($uri, $method->invoke($newInstanceClass)); } if (isset($methodAnnotations['SlimAnnotation\\Mapping\\Annotation\\PUT'])) { $app->put($uri, $method->invoke($newInstanceClass)); } }
$app = new Slim(array('debug' => true, 'log.level' => \Slim\Log::DEBUG, 'log.enabled' => true, 'log.writer' => new \Slim\LogWriter(fopen(dirname(__FILE__) . '/log/' . date('Y-M-d') . '.log', 'a')))); $app->get('/v1/monetizador/test', "ping"); //Cargos $app->get('/v1/monetizador/cargos', "cargos"); $app->post('/v1/monetizador/cargos', "cargos"); $app->post('/v1/monetizador/cargos/clientes:/id', "cargos"); //Tarjetas $app->get('/v1/monetizador/tarjetas', "cards"); $app->post('/v1/monetizador/tarjetas', "cardAdd"); $app->delete("/v1/monetizador/tarjetas/:id", "cardDelete"); // Cliente $app->post("/v1/monetizador/clientes", "cliente"); $app->get("/v1/monetizador/clientes", "clienteListar"); $app->get("/v1/monetizador/clientes/:id", "clienteListar"); $app->delete("/v1/monetizador/clientes/:id", "clienteEliminar"); $app->put("/v1/monetizador/clientes/:id", "clienteEditar"); // Cliente - Tarjeta $app->post('/v1/monetizador/tarjetas/clientes/:id', "cardAdd"); $app->get('/v1/monetizador/tarjetas/clientes/:id', "cards"); $app->delete("/v1/monetizador/clientes/:idcliente/tarjetas/:id", "cardDelete"); // Plan $app->post("/v1/monetizador/planes", "plan"); $app->get("/v1/monetizador/planes", "clienteListar"); $app->get("/v1/monetizador/planes/:id", "clienteListar"); $app->delete("/v1/monetizador/planes/:id", "clienteEliminar"); $app->put("/v1/monetizador/planes/:id", "clienteEditar"); /** * Recurso test * * El recurso Test es una funcion que verifica que la conectividad de los servicio * este disponible
<?php require 'config.php'; require 'Slim/Slim.php'; require 'BasicAuth.php'; use Slim\Slim; use Slim\Extras\Middleware\HttpBasicAuth; Slim::registerAutoloader(); $app = new Slim(); if (USE_ADMIN_LOGIN) { $app->add(new BasicAuth(ADMIN_USERNAME, ADMIN_PASSWORD, 'private', array(new Route('DELETE', '/records'), new Route('DELETE', '/explorations'), new Route('PUT', '/explorations'), new Route('POST', '/explorations')))); } //exploration routes $app->get('/explorations/', 'listExplorations'); $app->get('/explorations/:id', 'getExploration'); $app->put('/explorations/:id', 'saveExploration'); $app->post('/explorations/', 'saveExploration'); $app->delete('/explorations/:id', 'deleteExploration'); //record routes $app->get('/records/:arg', 'getRecord'); $app->get('/records/', function () use($app) { $req = $app->request->params('exploration_id'); getRecords($req); }); $app->delete('/records/:arg', 'deleteRecord'); //upload record routes $app->post('/records/submit/', 'submitRecord'); $app->post('/records/upload/', 'uploadRecordFile'); $app->run(); /* Exploration Methods */ function getExploration($arg)
require_once '../DAL/DAO/StudentDAO.php'; require_once '../DAL/Entity/Course.php'; require_once '../DAL/DAO/CourseDAO.php'; require_once '../DAL/Database.php'; require_once '../DAL/DAO/EnrollmentDAO.php'; require_once '../DAL/Entity/Enrollment.php'; require_once '../DAL/DAO/UserDAO.php'; require_once '../DAL/Entity/User.php'; use Slim\Slim; use Entity\Employee; use DAO\EmployeeDAO; Slim::registerAutoloader(); $app = new Slim(); $app->post('/employee', 'registerEmployee'); $app->get('/employees', 'getEmployees'); $app->put('/employee', 'updateEmployee'); $app->delete('/employee/:id', 'deleteEmployee'); $app->post('/student', 'registerStudent'); $app->get('/students', 'getStudents'); $app->put('/student', 'updateStudent'); $app->delete('/student/:id', 'deleteStudent'); $app->get('/courses', 'getCourses'); $app->post('/course', 'addCourse'); $app->put('/course', 'updateCourse'); $app->delete('/course/:id', 'deleteCourse'); $app->get('/enrollments', 'getEnrollments'); $app->post('/enrollment', 'addEnrollment'); $app->post('/login', 'login'); $app->get('/login', 'getStatus'); $app->get('/logout', 'logout'); $app->run();
$app->flash('joinSuccess', true); $app->redirect($app->urlFor('social-graph')); } else { // show the "try again" message. $app->render('home/index.mustache', array('error' => 'The username "' . $username . '" already exists. Please try again.')); } } else { // username field was empty $app->render('home/index.mustache', array('error' => 'Please enter a username.')); } }); // social - edit a user $app->put('/user/edit', function () use($app) { $params = json_decode($app->request->getBody()); $user = UserService::getByUsername($_SESSION['username']); $user->firstname = $params->firstname; $user->lastname = $params->lastname; UserService::save($user); $app->jsonResponse->build($user); })->name('user-edit'); /******************************** * Start Social Graph *******************************/ // social - friends - get list of friends and search for new ones $app->get('/friends', $isLoggedIn, function () use($app) { $user = UserService::getByUsername($_SESSION['username']); $following = UserService::following($_SESSION['username']); $suggestions = UserService::friendSuggestions($_SESSION['username']); $app->render('graphs/social/friends.mustache', array('user' => $user, 'following' => $following, 'suggestions' => $suggestions, 'unfollowUrl' => $app->urlFor('social-unfollow', array('userToUnfollow' => null)), 'followUrl' => $app->urlFor('social-follow', array('userToFollow' => null)))); })->name('social-friends'); // takes current user session and will follow :username, e.g. one way follow $app->get('/follow/:userToFollow', function ($userToFollow) use($app) {
/** * @SWG\Api( * path="/gas-stations/{gasStationId}", * @SWG\Operation( * method="PUT", * summary="Edit the information of a gas station", * type="GasStation", * nickname="editGasStation", * @SWG\Parameters( * @SWG\Parameter( * name="Accept", * description="The type of response that the web service client expects", * paramType="header", * required=true, * type="string", * enum="['application/json', 'application/xml']" * ), * @SWG\Parameter( * name="gasStationId", * description="ID of gas station that needs to be edited", * paramType="path", * required=true, * type="integer" * ), * @SWG\Parameter( * name="name", * description="The name of the gas station", * paramType="form", * required=false, * type="string" * ), * @SWG\Parameter( * name="social_reason", * description="The legal name of the gas station", * paramType="form", * required=false, * type="string" * ), * @SWG\Parameter( * name="address_line_1", * description="Street name and number of the gas station", * paramType="form", * required=false, * type="string" * ), * @SWG\Parameter( * name="address_line_2", * description="Name of the gas station neighborhood", * paramType="form", * required=false, * type="string" * ), * @SWG\Parameter( * name="location", * description="State and city name where the gas station is located", * paramType="form", * required=false, * type="string" * ), * @SWG\Parameter( * name="latitude", * description="Latitude coordinate", * paramType="form", * required=false, * type="double" * ), * @SWG\Parameter( * name="longitude", * description="Longitude coordinate", * paramType="form", * required=false, * type="double" * ) * ), * @SWG\ResponseMessages( * @SWG\ResponseMessage( * code=400, * message="Gas station data did not pass validation" * ), * @SWG\ResponseMessage( * code=404, * message="Gas station data not found" * ) * ) * ) * ) */ protected function editStation() { $this->app->put('/gas-stations/:id', function ($id) { $this->app->stationController->put($id); }); }
$app->post('/estadia', 'confirmarReserva'); //guardar Reserva $app->post('/estadia/update', 'updateEstadia'); //guardar Reserva $app->post('/estadia/checkIn', 'registrarCheckIn'); //guardar Reserva $app->post('/estadia/checkOut', 'registrarCheckOut'); //guardar Reserva $app->get('/hotel/calculo/:fechaIn/:fechaOut/:cId', 'calcularDiferenciasDiasyTotal'); $app->get('/noches/:fechaIn/:fechaOut', 'dias_transcurridos'); $app->post('/reservas', 'addReservation'); // Using Post HTTP Method and process getUser function $app->get('/reservas/:criterio', 'getReservas'); // Obtener todas las reservas para el metodo get $app->get('/reservas/:idR', 'getReservaItem'); $app->put('/reservas', 'addReservaPut'); //guardar Reserva $app->get('/habitacionesOcupantes/:estadia', 'getOcupantes'); //guardar Reserva $app->post('/habitacionesOcupantes', 'addcupantes'); //guardar Reserva $app->post('/filesUpload', 'uploadFiles'); $app->get('/productos', 'getProductos'); $app->get('/catProductos', 'getCatProductos'); $app->post('/pedidos', 'addPedido'); $app->get('/pedidos/:estadia', 'getPedidos'); $app->get('/factura/:cuenta', 'getFactura'); $app->run(); function getServiciosCliente($nombre) { $request = Slim::getInstance()->request();
/** * @param string $routeName * @param string $tableName * @param callable $customCRUDFunction * @param string $displayName */ public function add($routeName, $customCRUDFunction = null, $tableName = null, $displayName = null) { if ($tableName == null) { $tableName = $routeName; } $this->tableList[$routeName] = $tableName; $this->tableDisplayName[$routeName] = $displayName; $this->routeNameList[] = $routeName; /* * Page Group (ListView, CreateView, EditView) */ $this->slim->group("/" . $this->groupName . "/" . $routeName, function () use($routeName, $customCRUDFunction, $tableName) { $this->slim->get("/", function () use($routeName) { $this->slim->redirectTo("_louisCRUD_" . $routeName); }); /* * ListView */ $this->slim->get("/list(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->renderListView(); } })->name("_louisCRUD_" . $routeName); /* * Create */ $this->slim->get("/create(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->createFunction != null) { $createFunction = $this->createFunction; $result = $createFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force Hide ID field $this->field("id")->hide(); if ($this->isEnabledCreate()) { $this->renderCreateView(); } }); /* * Edit */ $this->slim->get("/edit/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean first $this->loadBean($id); // ID must be hidden $this->field("id")->hide(); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // If user show the ID field, force set it to readonly $this->field("id")->setReadOnly(true); if ($this->isEnabledEdit()) { $this->renderEditView(); } }); /* * Export Excel */ $this->slim->map("/export(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->exportFunction != null) { $exportFunction = $this->exportFunction; $result = $exportFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // TODO: isEnabledExport(); $this->renderExcel(); })->via('GET', 'POST'); }); /* * API Group, RESTful style. */ $this->slim->group("/" . $this->apiGroupName . "/" . $routeName, function () use($routeName, $customCRUDFunction, $tableName) { /* * JSON for Listview */ $this->slim->map("/list(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { $this->enableJSONResponse(); // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->getJSONList(); } return; })->via('GET', 'POST'); /* * For Datatables */ $this->slim->map("/datatables(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { $this->enableJSONResponse(); // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->getListViewJSONString(); } return; })->via('GET', 'POST'); /* * View a bean * PUT /api/{tableName}/{id} */ $this->slim->get("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Edit Function if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledEdit()) { $json = $this->getJSON(false); $this->enableJSONResponse(); echo $json; } }); /* * Insert a bean * POST /api/{tableName} */ $this->slim->post("(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Global Function $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } // Custom Create Function if ($this->createFunction != null) { $createFunction = $this->createFunction; $result = $createFunction($p1, $p2, $p3, $p4, $p5); } if ($result === false) { return; } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledCreate()) { $jsonObject = $this->insertBean($_POST); $this->enableJSONResponse(); echo json_encode($jsonObject); } else { // TODO: Should be json object echo "No permission"; } }); /* * Update a bean * PUT /crud/{tableName}/{id} */ $this->slim->put("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Create Function if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledEdit()) { $jsonObject = $this->updateBean($this->slim->request()->params()); $this->enableJSONResponse(); echo json_encode($jsonObject); } }); /* * Delete a bean * DELETE /crud/{tableName}/{id} */ $this->slim->delete("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); $this->enableJSONResponse(); $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Delete Function if ($this->deleteFunction != null) { $deleteFunction = $this->deleteFunction; $result = $deleteFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledDelete()) { $this->deleteBean(); $result = new \stdClass(); $result->status = "succ"; echo json_encode($result); } }); }); }
echo '{"error":{"text":' . $e->getMessage() . '}}'; } }); /** * Route to update an emoji. */ $app->put('/emojis/:id', function ($id) use($app) { try { $app->response()->headers("Content-Type", "application/json"); $authHeader = $app->request->headers->get('Authorization'); $decodedToken = Reusable::tokenVerify($authHeader); if ($decodedToken) { $emoji = json_decode($app->request->getBody(), true); $emojiUpdate = Emoji::with('user')->where('id', $id)->first(); if ($emojiUpdate->user->token !== 1) { echo json_encode(array("status" => "Bad request", "message" => "Log in to update the emoji!")); } else { $emojiUpdate->update($emoji); echo json_encode(array("status" => "success", "message" => "Emoji updated!")); } } } catch (\PDOException $e) { echo '{"error":{"text":' . $e->getMessage() . '}}'; } }); /** * Route to partially update an emoji. */ $app->patch('/emojis/:id', function ($id) use($app) { try { $app->response()->headers("Content-Type", "application/json");