private function setNotFoundAction() { $app = $this->app; $this->app->notFound(function () use($app) { $logger = new Logger(); $content = "Invalid url called [" . $app->request->getMethod() . "]" . $app->request->getURI(); $logger->error($content); $app->response->setStatusCode(404, "Not Found")->sendHeaders(); Debug::output($content); }); }
/** * Tests the notFound * * @issue T169 * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-11-06 */ public function testMicroNotFoundT169() { $this->specify("MVC Micro notFound doesn't work", function () { $handler = new \RestHandler(); $app = new Micro(); $app->get("/api/site", [$handler, "find"]); $app->post("/api/site/save", [$handler, "save"]); $flag = false; $app->notFound(function () use(&$flag) { $flag = true; }); $_SERVER["REQUEST_METHOD"] = "GET"; $_GET["_url"] = "/fourohfour"; $app->handle(); expect($flag)->true(); }); }
// return $auth; //}; // CoreController if ($app['controllers']['core']) { $core = new MicroCollection(); // Set the handler & prefix $core->setHandler(new CoreController($app)); $core->setPrefix('/'); // Set routers $core->get('/', 'index'); $app->mount($core); } // UsersController if ($app['controllers']['user']) { $users = new MicroCollection(); // Set the handler & prefix $users->setHandler(new UserController($app)); $users->setPrefix('/user'); // Set routers $users->post('/', 'create'); $users->put('/{id}', 'update'); $users->delete('/{id}', 'delete'); $users->get('/', 'userList'); $users->get('/{id}', 'info'); $app->mount($users); } // Not Found $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); }); $app->handle();
foreach ($status->getMessage() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); // Deletes robots based on primary key $app->delete('/api/robots/{id:[0-9]+}', function ($id) use($app) { $phql = "DELETE FROM Robots WHERE id = :id:"; $status = $app->modelsManager->executeQuery($phql, array('id' => $id)); // Create a response $response = new Response(); if ($status->success() == true) { $response->setJsonContent(array('status' => 'OK')); } else { // Change the HTTP status $response->setStatusCode(409, "Conflict"); $errors = array(); foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo 'This is crazy, but this page was not found!'; }); $app->handle();
* Configure HTTP response */ $app->response->setHeader('Access-Control-Allow-Origin', '*'); $app->response->setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization'); /* * Add collections for routing */ $collections = glob($config->app->collectionsDir . '*.php'); foreach ($collections as $collection) { $app->mount(include_once $collection); } /** * Handle the request */ $app->notFound(function () use($app) { throw new Exception('Not Found', 404); }); $app->after(function () use($app) { $data = $app->getReturnedValue(); $app->response->setContentType('application/json', 'utf-8'); $app->response->setStatusCode($data['code'], null); $app->response->setJsonContent($data['content']); $app->response->send(); }); $app->handle(); } catch (Exception $e) { $code = $e->getCode() ? $e->getCode() : 500; $app->response->setStatusCode($code, $e->getMessage()); $app->response->setContent($e->getMessage()); $app->response->send(); }
<?php use Phalcon\Mvc\Micro; use Phalcon\Http\Response; require "config/config.php"; require "config/services.php"; $app = new Micro($di); $app->get('/', function () use($app) { echo $app['view']->render('index'); }); $app->notFound(function () use($app) { echo $app['view']->render('404'); }); $app->error(function () use($app) { echo $app['view']->render('500'); }); $app->handle();
// api 规则路由 $apiRegister = (require_once APP_PATH . '/config/register.php'); // 注册命名空间 $loader = new \Phalcon\Loader(); $loader->registerNamespaces($apiRegister['namespace'])->register(); foreach ($apiRegister['list'] as $class => $conf) { $index = new Micro\Collection(); $index->setHandler(new $class()); $index->setPrefix($conf['prefix']); foreach ($conf['router'] as $router) { $index->{$router}[0]($router[1], $router[2]); } $app->mount($index); } // 设置数据库连接 $di->set('db', function () use($config) { $config = $config->get('database')->toArray(); $dbAdapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config['adapter']; $connection = new $dbAdapter($config); return $connection; }); // 设置配置 $di->set('config', function () use($config) { return $config; }); // 未找到配置 $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo json_encode(array('ret' => 404, 'message' => 'not found')); }); $app->handle();
//Register Directories $loader = new \Phalcon\Loader(); $loader->registerDirs(array(__DIR__ . '/app/models/', __DIR__ . '/app/controllers/', __DIR__ . '/app/classes/'))->register(); // Use composer autoloader to load vendor classes require_once __DIR__ . '/vendor/autoload.php'; //Create the app $app = new Micro(); // Mount the routes $routes = (include_once __DIR__ . '/app/config/routes.php'); foreach ($routes as $route) { $app->mount($route); } // Default Response $app->get('/', function () { return Rs::p(1, 'API is up!'); }); //Add any filter before running the route $app->before(function () use($app) { //You may want to add some basic auth in order to access the REST API }); //This is executed after running the route $app->after(function () use($app) { }); // Not Found $app->notFound(function () use($app) { return Rs::p(0, 'Not Found', [], 404); }); $app->handle(); } catch (\Exception $e) { return Rs::p(0, 'There was an error processing your request', $e->getMessage(), 400); }
<?php use Phalcon\Mvc\Micro; use Phalcon\Http\Response; $app = new Micro(); $app->get('/api/frameworks', function () { $response = new Response(); $response->setContentType('application/json'); $data = [['name' => 'Zend', 'version' => '2.4.8'], ['name' => 'Symfony', 'version' => '2.7.5'], ['name' => 'Silex', 'version' => '1.3.4'], ['name' => 'Phalcon', 'version' => '2.0.8']]; $response->setJsonContent($data); return $response; }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, 'Not Found')->sendHeaders(); echo 'The requested resource is not found'; }); $app->handle();
return new PdoMysql(array("host" => "localhost", "username" => "root", "password" => "", "dbname" => "new-encounter")); }); $app = new Micro($di); $app->get('/', function () { echo "Singou Encounter Back End API Server"; }); $app->get('/token', function () { return router('User', 'login', func_get_args()); }); $app->delete('/token', function () { return router('User', 'logout', func_get_args()); }); $app->get('/lottery', function () { return router(''); }); $app->post('/lottery', function () { return router(''); }); $app->notFound(function () { return router('Base', 'error', array('0001', 404)); }); $app->handle(); } catch (Exception $e) { echo "Exception: ", $e->getMessage(); } function router($controller, $action, $parameters) { $class_name = $controller . 'Controller'; $controller = new $class_name(); return call_user_func_array(array($controller, $action), $parameters); }
if ($source) { $source->setData($put->data); $source->setType($put->type); $source->setName($put->name); if ($source->save()) { $app->response->setStatusCode(200, 'OK'); $app->response->setJsonContent(array('status' => 'OK'))->send(); } } else { $app->response->setStatusCode(404, 'Not Found'); $app->response->setJsonContent(array('status' => 'Not Found'))->send(); } }); // Delete existing source $app->delete('/sources/{id}', function ($id) use($app) { $source = Tabs\Models\Sources::findById((string) $id); if ($source) { if ($source->delete()) { $app->response->setStatusCode(200, 'OK'); $app->response->setJsonContent(array('status' => 'OK'))->send(); } } else { $app->response->setStatusCode(404, 'Not Found'); $app->response->setJsonContent(array('status' => 'Not Found'))->send(); } }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found"); $app->response->setJsonContent(array('status' => 'Not Found'))->send(); }); $app->handle();
}); /** * Registering an autoloader */ $loader = new Loader(); $loader->registerDirs(array($config->application->modelsDir))->register(); /** * Starting the application */ $app = new Micro(); /** * Add your routes here */ $app->get('/', function () { require __DIR__ . "/../views/index.phtml"; }); /** * Not found handler */ $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); require __DIR__ . "/../views/404.phtml"; }); /** * Handle the request */ $app->handle(); } catch (\Exception $e) { echo $e->getMessage(), PHP_EOL; echo $e->getTraceAsString(); }
* fetch all racing venues */ $app->get('/venues/{sports_id:[0-9]*}', function ($sport_id) use($app, $response) { $code = 200; $responseText = 'ok'; $data = array(); $sql = "SELECT * FROM venue WHERE sport_id = " . (int) $sport_id; $results = $app->modelsManager->executeQuery($sql); foreach ($results as $row) { $data[] = array('venue_id' => $row->venue_id, 'name' => $row->name); } $response->send($code, $responseText, $data); }); /** * fetch feed venue settings */ $app->get('/feed/venue/{venue_id:[0-9]*}', function ($venue_id) use($app, $response) { $code = 200; $responseText = 'ok'; $data = array(); $sql = "SELECT va.venue_id, va.venue_alias_id, va.feed_id, va.name, f.name as feed_name, fvp.priority FROM venueAlias va\n LEFT JOIN feed f ON (va.feed_id = f.feed_id)\n LEFT JOIN feedVenuePriority fvp ON (va.feed_id = fvp.feed_id AND va.venue_id = fvp.venue_id)\n WHERE va.venue_id = " . (int) $venue_id; $results = $app->modelsManager->executeQuery($sql); foreach ($results as $row) { $data[] = array('venue_id' => $row->venue_id, 'venue_alias_id' => $row->venue_alias_id, 'feed_id' => $row->feed_id, 'feed_name' => $row->feed_name, 'name' => $row->name, 'priority' => $row->priority); } $response->send($code, $responseText, $data); }); $app->notFound(function () use($app, $response) { $response->send(404, 'Not Found', array('error' => 'Not Supported Operation')); }); $app->handle();
$user = new Contas(); $user->responsavel = $app->request->getPost('responsavel'); $user->cliente = $app->request->getPost('cliente'); $user->host = $app->request->getPost('host'); $user->database = $app->request->getPost('database'); $response = new Response(); $response->setHeader('Content-Type', 'application/xml'); if ($user->save()) { $response->setStatusCode(201, 'Created'); $response->setContent("<?xml version='1.0' encoding='ISO-8859-1'?><response><status>OK</status><mensagem>{$user->key}</mensagem></response>"); } else { $response->setStatusCode(400, 'Invalid Request'); $errors = array(); foreach ($user->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setContent("<?xml version='1.0' encoding='ISO-8859-1'?><response><status>ERROR</status><mensagem>{$errors[0]}</mensagem></response>"); } return $response; }); ################################################## ####### NOT FOUND ################################################## // Caso a url acessada não existe retorna uma mensagem de erro. $app->notFound(function () use($app) { $response = new Response(); $response->setStatusCode(404, 'Not Found'); $response->setContent("<?xml version='1.0' encoding='ISO-8859-1'?><response><status>ERROR</status><mensagem>Requisição inválida, m´dtodo não encontrado </mensagem></response>"); return $response; }); $app->handle();