public function formAction() { $app = new \Phalcon\Mvc\Micro(); echo $app->request->getRawBody(); $app->post('/api/robots', function () use($app) { $robot = json_decode($app->request->getRawBody()); print_r($robot); }); }
public function testMicroEvents() { $trace = array(); $eventsManager = new Phalcon\Events\Manager(); $eventsManager->attach('micro', function ($event) use(&$trace) { $trace[$event->getType()] = true; }); $app = new Phalcon\Mvc\Micro(); $app->setEventsManager($eventsManager); $app->map('/blog', function () { }); $app->handle('/blog'); $this->assertEquals($trace, array('beforeHandleRoute' => true, 'beforeExecuteRoute' => true, 'afterExecuteRoute' => true, 'afterHandleRoute' => true)); }
public function testMicroCollectionsLazy() { $app = new Phalcon\Mvc\Micro(); $collection = new Phalcon\Mvc\Micro\Collection(); $collection->setHandler('PersonasLazyController', true); $collection->map('/', 'index'); $collection->map('/edit/{number}', 'edit'); $app->mount($collection); $app->handle('/'); $this->assertEquals(PersonasLazyController::getEntered(), 1); $app->handle('/edit/100'); $this->assertEquals(PersonasLazyController::getEntered(), 101); }
/** * Tests the notFound * * @issue T169 * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-11-06 */ public function testMicroNotFound_T169() { $handler = new RestHandler($this); $app = new \Phalcon\Mvc\Micro(); $app->get('/api/site', array($handler, 'find')); $app->post('/api/site/save', array($handler, 'save')); $flag = false; $app->notFound(function () use(&$flag) { $flag = true; }); $_SERVER['REQUEST_METHOD'] = 'GET'; $_GET['_url'] = '/fourohfour'; $app->handle(); $this->assertTrue($flag); }
<?php $app = new Phalcon\Mvc\Micro(); $app->notFound(function () use($app) { $app->response->setStatusCode(404, 'Not Found')->sendHeaders(); echo 'Page not found.'; }); // begin route config $app->get('/api/test', function () { echo "HELLO WORLD"; }); $app->handle();
<?php try { $config = (include __DIR__ . "/../app/config/config.php"); include __DIR__ . "/../app/config/loader.php"; include __DIR__ . "/../app/config/services.php"; include $config->application->services->dir . "fonctions.php"; $app = new \Phalcon\Mvc\Micro(); $app->setDI($di); $app->get('/configuration/{configuration}', function ($configuration) use($di, $app) { $configArray = explode(".", $configuration); $configKey = $configArray[0]; $encoding = "json"; if (count($configArray) === 2) { $encoding = $configArray[1]; } // Gerer le cas où on appelle une configuration inexistante et où il y aurait une erreur dans la configuration. if (isset($di->getConfig()->configurations[$configKey])) { $xmlPath = $di->getConfig()->configurations[$configKey]; } else { $xmlPath = $di->getConfig()->configurationsDir . $configKey . '.xml'; } if (!file_exists($xmlPath) && !curl_url_exists($xmlPath)) { $app->response->setStatusCode(404, "Not Found"); $error = new stdClass(); $error->error = "La configuration « {$configuration} » n'existe pas!"; $app->response->send(); die(json_encode($error)); } if ($encoding === "json") { $app->response->setContentType('application/json; charset=UTF-8')->sendHeaders();
$di->setShared('requestData', function () { $in = file_get_contents('php://input'); $json = json_decode($in, true); // se nao foi enviado um json retorna o que foi enviado if ($json === null) { parse_str($in, $post_vars); return $post_vars; } return $json; }); /** * Out application is a Micro application, so we mush explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * @var $app */ $app = new Phalcon\Mvc\Micro(); $app->setDI($di); /** * Before every request, make sure user is authenticated. * Returning true in this function resumes normal routing. * Returning false stops any route from executing. */ $app->before(function () use($app, $di) { $matchedRoute = $app->getRouter()->getMatchedRoute()->getName(); // All options requests get a 200, then die if ($app->__get('request')->getMethod() == 'OPTIONS') { $app->response->setStatusCode(200, 'OK')->sendHeaders(); exit; } if (preg_match("/-allow/", $matchedRoute)) { return true;
*/ $di->setShared('requestBody', function () { $in = file_get_contents('php://input'); $in = json_decode($in, FALSE); // JSON body could not be parsed, throw exception if ($in === null) { throw new HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'internalCode' => 'REQ1000', 'more' => '')); } return $in; }); /** * Out application is a Micro application, so we mush explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * @var $app */ $app = new Phalcon\Mvc\Micro(); $app->setDI($di); /** * Before every request, make sure user is authenticated. * Returning true in this function resumes normal routing. * Returning false stops any route from executing. */ /* This will require changes to fit your application structure. It supports Basic Auth, Session auth, and Exempted routes. It also allows all Options requests, as those tend to not come with cookies or basic auth credentials and Preflight is not implemented the same in every browser. */ $app->before(function () use($app, $di) {
https://github.com/elbereth/dashninja-fe Dash Ninja is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Dash Ninja is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ // Load configuration and connect to DB require_once 'libs/db.inc.php'; // Create and bind the DI to the application $app = new \Phalcon\Mvc\Micro(); $router = $app->getRouter(); $router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); // ******************************************************* // Non-Auth required // ******************************************************* // Get blocks detail + stats // Parameters: // testnet=0|1 // interval=interval (optional, default is P1D for 1 day) $app->get('/api/blocks', function () use($app, &$mysqli) { //Create a response $response = new Phalcon\Http\Response(); $response->setHeader('Access-Control-Allow-Origin', '*'); $response->setHeader("Content-Type", "application/json"); $request = $app->request;
/** * Creates the autoloader and register namespaces of each module */ $loader = new Loader(); $loader->registerNamespaces($modules)->register(); /** * Initialize each module executing Module.php of each one. * Save module name to be used when routes will be registered. */ $modulesName = array(); foreach ($modules as $namespace => $path) { $modulesName[] = basename($path); $module = $namespace . '\\Module'; $module = new $module(); } $app = new Phalcon\Mvc\Micro(); $app->setDI($di); /** * Add exception handler to show them in json */ set_exception_handler(function ($e) use($app) { $logger = new FileAdapter('debug.log'); $logger->warning($e->getMessage()); if (method_exists($e, 'send')) { $e->send(); } $logger->error($e->getTraceAsString()); }); /** * Mount all collections (Makes routes active). * @todo improve this block of code
*/ $di->setShared('requestBody', function () { $in = file_get_contents('php://input'); $in = json_decode($in, FALSE); // JSON body could not be parsed, throw exception if ($in === null) { throw new HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'internalCode' => 'REQ1000', 'more' => '')); } return $in; }); /** * Out application is a Micro application, so we mush explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * @var $app */ $app = new Phalcon\Mvc\Micro(); $app->setDI($di); /** * Before every request, make sure user is authenticated. * Returning true in this function resumes normal routing. * Returning false stops any route from executing. */ /* This will require changes to fit your application structure. It supports Basic Auth, Session auth, and Exempted routes. It also allows all Options requests, as those tend to not come with cookies or basic auth credentials and Preflight is not implemented the same in every browser. */ /*
<?php try { $config = (include __DIR__ . "/config/config.php"); include __DIR__ . "/config/loader.php"; include __DIR__ . "/config/services.php"; $app = new \Phalcon\Mvc\Micro(); $app->setDI($di); $app->map('/', "request")->via(array('GET', 'POST')); $app->handle(); } catch (\Exception $e) { $debug = $config['application']['debug']; $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'; header($protocol . ' 400 Bad Request'); if (isset($debug) && $debug === true) { die(json_encode(array("result" => "failure", "error" => $e->getMessage(), "stack" => $e->getTraceAsString()))); } else { die(json_encode(array("result" => "failure", "error" => "Une erreur s'est produite."))); } } function request() { global $app; $httprequest = new Phalcon\Http\Request(); $datain = $httprequest->get(); $data = array(); foreach ($datain as $key => $value) { $data[strtolower($key)] = $value; } $filter = new \Phalcon\Filter(); $request = $filter->sanitize($data["request"], array("string", "lower"));
public function testMicroStopMiddlewareClasses() { Phalcon\DI::reset(); $app = new Phalcon\Mvc\Micro(); $app->map('/api/site', function () { return true; }); $middleware = new MyMiddlewareStop(); $app->before($middleware); $app->before($middleware); $app->after($middleware); $app->after($middleware); $app->finish($middleware); $app->finish($middleware); $app->handle('/api/site'); $this->assertEquals($middleware->getNumber(), 3); }
error_reporting(E_ALL); define('APP_PATH', realpath('..')); define('HEADERIMG_PATH', __DIR__ . '/update/headerimg'); define('TEMP_PATH', __DIR__ . '/temp'); define('__HOST__', 'http://192.168.0.179'); define('METO_HEADER_IMG', __HOST__ . '/update/headerimg/'); define('METO_HEADER_VDO', __HOST__ . '/update/headervideo/'); try { $config = (include APP_PATH . "/app/config/config.php"); include APP_PATH . "/app/config/loader.php"; include APP_PATH . "/app/config/services.php"; include APP_PATH . "/app/common/common.php"; /** * Handle the request */ $app = new \Phalcon\Mvc\Micro(); $app->setDI($di); $app->setEventsManager($eventManager); $app->response->setContentType('text/json', 'UTF-8'); $app->response->sendHeaders(); /** * 路由 */ //注册 $app->post('/sendcode', [$app->auth, 'getYZM']); $app->post('/checkphone', [$app->auth, 'checkphone']); $app->post('/headerimg', [$app->auth, 'uploadHeaderImg']); $app->post('/register', [$app->auth, 'register']); //登陆 $app->post('/login', [$app->auth, "login"]); //登出
//includes include 'lib/XmlStringStreamer.php'; include 'lib/XmlStringStreamer/ParserInterface.php'; include 'lib/XmlStringStreamer/StreamInterface.php'; include 'lib/XmlStringStreamer/Parser/StringWalker.php'; include 'lib/XmlStringStreamer/Parser/UniqueNode.php'; include 'lib/XmlStringStreamer/Stream/File.php'; include 'lib/XmlStringStreamer/Stream/Stdin.php'; include 'lib/xml2json.php'; require 'lib/mailer/swift_required.php'; require 'lib/Utils.php'; //Config include "config.php"; //Bootstrap app $di = new \Phalcon\Di\FactoryDefault(); $app = new \Phalcon\Mvc\Micro($di); //Set logger $logger = new \Phalcon\Logger\Adapter\File(LOG_FILE); //Set error handler set_error_handler(function ($errno, $errstr, $errfile, $errline) use($app, $logger) { $logger->error("{$errno}, {$errstr}, {$errfile}, {$errline}"); }); //Set falar error logging register_shutdown_function(function () use($logger) { $error = error_get_last(); if (isset($error['type'])) { $logger->error("{$error['type']} {$error['message']} {$error['file']} {$error['line']}"); } }); //Set mailer $transport = Swift_SmtpTransport::newInstance(MAIL_SMTP_SERVER, 465, 'ssl');
<?php $loader = new \Phalcon\Loader(); $loader->registerDirs([__DIR__ . '/models/'])->register(); $di = new \Phalcon\DI\FactoryDefault(); $di->set('db', function () { return new \Phalcon\Db\Adapter\Pdo\Mysql(['host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'time']); }); $app = new \Phalcon\Mvc\Micro($di); /** * Tasks */ $app->get('/tasks', function () use($app) { $phql = "SELECT * FROM Tasks"; $tasks = $app->modelsManager->executeQuery($phql); $data = new StdClass(); $data->tasks = []; foreach ($tasks as $task) { $data->tasks[] = ['id' => $task->id, 'name' => $task->name, 'shortDescription' => $task->short_description, 'longDescription' => $task->long_description, 'day' => $task->day, 'started' => $task->started, 'completed' => $task->completed]; } echo json_encode($data); }); $app->post('/tasks', function () use($app) { $request = $app->request->getJsonRawBody()->task; $name = $request->name; $short = $request->shortDescription; $long = $request->longDescription; $day = $request->day; $phql = "INSERT INTO Tasks(name, short_description, long_description, day, started, completed) VALUES(:name:, :short:, :long:, :day:, null, null)"; $status = $app->modelsManager->executeQuery($phql, ['name' => $name, 'short' => $short, 'long' => $long, 'day' => $day]); $response = new \Phalcon\Http\Response();
<?php $loader = new \Phalcon\Loader(); $loader->registerDirs(array(__DIR__ . '/models/'))->register(); $app = new \Phalcon\Mvc\Micro(); $app->get('/products/find', function () { foreach (Products::find() as $product) { echo $product->name, '<br>'; } }); $app->handle();
<?php $app = new Phalcon\Mvc\Micro(); //Executed before every route executed //Return false cancels the route execution $app->before(function () use($app) { if ($app['session']->get('auth') == false) { return false; } return true; }); $app->map('/api/robots', function () { return array('status' => 'OK'); }); $app->after(function () use($app) { //This is executed after the route is executed echo json_encode($app->getReturnedValue()); }); $app->finish(function () use($app) { //This is executed when the request has been served });
<?php use Phalcon\Mvc\Micro\Collection; /** * Our application is a Micro application, so we mush explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * * @var $app */ $app = new Phalcon\Mvc\Micro(); $app->setDI($di); /** * Before every request: * Returning true in this function resumes normal routing. * Returning false stops any route from executing. */ $app->before(function () use($app, $di) { // set standard CORS headers before routing just incase no valid route is found $config = $di->get('config'); $app->response->setHeader('Access-Control-Allow-Origin', $config['application']['corsOrigin']); return true; }); /** * Mount all of the collections, which makes the routes active. */ foreach ($di->get('collections') as $collection) { $app->mount($collection); } /** * The base route return the list of defined routes for the application. * This is not strictly REST compliant, but it helps to base API documentation off of.
<?php try { $app = new Phalcon\Mvc\Micro(); // Setting up the database connection $app['db'] = function () { return new \Phalcon\Db\Adapter\Pdo\Mysql(array('dsn' => 'host=localhost;dbname=hello_world;charset=utf8', 'username' => 'benchmarkdbuser', 'password' => 'benchmarkdbpass', 'persistent' => true)); }; // Setting up the view component (seems to be required even when not used) $app['view'] = function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(__DIR__ . '/../views/'); $view->registerEngines(array(".volt" => function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => __DIR__ . "/../compiled-templates/", "compiledExtension" => ".c", "compiledSeparator" => '_')); return $volt; })); return $view; }; $app->map('/json', function () { header("Content-Type: application/json"); echo json_encode(array('message' => 'Hello, World!')); }); // $app->map('/db', function () use($app) { $db = $app['db']; $queries = $app->request->getQuery('queries', null, 1); $worlds = array(); for ($i = 0; $i < $queries; ++$i) { $worlds[] = $db->fetchOne('SELECT * FROM world WHERE id = ' . mt_rand(1, 10000), Phalcon\Db::FETCH_ASSOC); }
<?php use Phalcon\Di\FactoryDefault as DefaultDI, Phalcon\Loader; require '../autoload.php'; require '../services.php'; //die(var_dump($di->getShared('authorizationServer'))); /** * Out application is a Micro application, so we mush explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * @var $app */ $app = new Phalcon\Mvc\Micro(); $app->setDI($di); /** * Mount all of the collections, which makes the routes active. */ foreach ($di->get('collections') as $collection) { $app->mount($collection); } /** * The base route return the list of defined routes for the application. * This is not strictly REST compliant, but it helps to base API documentation off of. * By calling this, you can quickly see a list of all routes and their methods. */ $app->get('/', function () use($app) { $routes = $app->getRouter()->getRoutes(); $routeDefinitions = ['GET' => [], 'POST' => [], 'PUT' => [], 'PATCH' => [], 'DELETE' => [], 'HEAD' => [], 'OPTIONS' => []]; /* @var $route Phalcon\Mvc\Router\Route */ foreach ($routes as $route) { $method = $route->getHttpMethods(); $routeDefinitions[$method][] = $route->getPattern();
<?php $app = new Phalcon\Mvc\Micro(); $app->get('/say/hello/{name}', function ($name) { echo "Hello ", $name, "!"; }); $app->handle();
<?php // Register the various resources needed for the execution (classes, paths, database) include "utils.php"; $loader = new Phalcon\Loader(); $loader->registerDirs(array(__DIR__ . '/models/'))->register(); $di = new Phalcon\DI\FactoryDefault(); $di->set('db', function () { return new Phalcon\Db\Adapter\Pdo\Sqlite(array("dbname" => "./chatroom.sqlite")); }); // Initialization $app = new Phalcon\Mvc\Micro($di); $app->getRouter()->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); //////////////////////////////////////////////////////// //////////////////////// ROUTES //////////////////////// //////////////////////////////////////////////////////// // Test call. $app->get('/chat/test', function () { echo json_encode(array('name' => 'Platform is up, check the database in case there are problems!')); }); // Get the list of all the active users in the chat. $app->get('/users', function () use($app) { $phql = "SELECT username, active, access_timestamp\n \t\tFROM Users\n \t\tWHERE active = 1 \n \t\tORDER BY access_timestamp DESC"; $users = $app->modelsManager->executeQuery($phql); $data = array(); foreach ($users as $user) { $data[] = array('id' => $user->id, 'active' => $user->active, 'access_timestamp' => $user->access_timestamp); } echo json_encode($data); }); // Get messages per pair of users.
<?php $app = new Phalcon\Mvc\Micro(); $app->get('/say/welcome/{name}', function ($name) { echo "<h1>Welcome {$name}!</h1>"; }); $app->handle();
*/ //error_reporting(0); ini_set('display_errors', 1); $config = (include __DIR__ . '/../app/config/config.php'); /** * Read auto-loader */ include __DIR__ . '/../app/config/loader.php'; /** * Read services */ include __DIR__ . '/../app/config/services.php'; /** * Create Application */ $app = new \Phalcon\Mvc\Micro($di); /** * Add your routes here */ /** * Expose the /v1/currency end point */ $currency = new MicroCollection(); $currency->setHandler('CurrencyController', true); $currency->setPrefix('/v1/currency'); $currency->post('/', 'addCurrency'); $currency->get('/', 'getAllCurrencies'); $currency->put('/{code}', 'updateCurrency'); $currency->get('/{code}', 'getCurrency'); $currency->delete('/{code}', 'deleteCurrency'); $app->mount($currency);
/** * Read the configuration */ $config = (include APP_PATH . "/app/config/config.php"); /** * Read auto-loader */ include APP_PATH . "/app/config/loader.php"; /** * Read services */ include APP_PATH . "/app/config/services.php"; /** * Handle the request */ $app = new \Phalcon\Mvc\Micro($di); $app->getRouter()->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); $app->before(new App\Middleware\OAuthMiddleware()); /** * Mount routes collections */ $collections = (include APP_PATH . '/app/collections/collections.php'); foreach ($collections as $collection) { $app->mount($collection); } $app->handle(); } catch (\Exception $e) { if ($app->config->debug) { echo $e->getMessage() . '<br>'; echo '<pre>' . $e->getTraceAsString() . '</pre>'; }
$response->send(); $authinfo = false; return false; } elseif ($authinfo['HubEnabled'] != '1') { $response = new Phalcon\Http\Response(); $response->setStatusCode(401, "Unauthorized"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array('Hub is disabled (Access denied)'))); $response->send(); return false; } // We passed! Peer is authorized! } } }); //Create and bind the DI to the application $app = new \Phalcon\Mvc\Micro(); $app->setEventsManager($eventManager); $router = $app->getRouter(); $router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); // ============================================================================ // BALANCES (for dmnbalance) // ---------------------------------------------------------------------------- // End-point to retrieve all pubkeys and last updates // HTTP method: // GET // Parameters: // None // ============================================================================ $app->get('/balances', function () use($app, &$mysqli) { global $authinfo; //Create a response
<?php $app = new Phalcon\Mvc\Micro(); $collection = new Phalcon\Mvc\Micro\Collection(); $collection->setHandler(new PostsController()); $collection->get('/posts/edit/{id}', 'edit'); $app->mount($collection);
<?php use App\Constants\Services as AppServices; // Setup up environment variable $application_env = getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'; /** @var \PhalconRest\Http\Response $response */ $response = null; try { // Read the configuration based on env $config = (require __DIR__ . "/../app/bootstrap/config.php"); // Include loader require __DIR__ . "/../app/bootstrap/loader.php"; // Setup all required services (DI) $di = (require __DIR__ . "/../app/bootstrap/services.php"); // Instantiate main application $app = new \Phalcon\Mvc\Micro($di); // Attach the EventsManager to the main application in order to attach Middleware $eventsManager = $app->di->get(AppServices::EVENTS_MANAGER); $app->setEventsManager($eventsManager); // Attach Middleware to EventsManager require __DIR__ . "/../app/bootstrap/middleware.php"; // Mount Collections require __DIR__ . "/../app/bootstrap/collections.php"; // Other routes $app->get('/', function () use($app) { /** @var Phalcon\Mvc\View\Simple $view */ $view = $app->di->get(AppServices::VIEW); return $view->render('general/index'); }); $app->get('/proxy.html', function () use($app, $config) { /** @var Phalcon\Mvc\View\Simple $view */
/** * If our request contains a body, it has to be valid JSON. This parses the * body into a standard Object and makes that vailable from the DI. If this service * is called from a function, and the request body is nto valid JSON or is empty, * the program will throw an Exception. */ $di->setShared('requestBody', function () { $in = file_get_contents('php://input'); $in = json_decode($in, FALSE); // JSON body could not be parsed, throw exception if ($in === null) { throw new \PhalconRest\Exceptions\HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'internalCode' => 'REQ1000', 'more' => '')); } return $in; }); $app = new Phalcon\Mvc\Micro(); $app->setDI($di); $app->before(function () use($app, $di) { if ($app->request->getMethod() == 'OPTIONS') { return true; } switch ($app->getRouter()->getRewriteUri()) { case '/v1/users/login/': case '/v1/users/login_jwt/': case '/v1/users/register/': case '/v1/reports/summary': case '/v1/reports/staff': case '/v1/reports/details': case '/example/route': return true; break;