12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- use Demo\User;
- use Silex\Application;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\Response;
- //Request::setTrustedProxies(array('127.0.0.1'));
- $app->get('/', function () use ($app) {
- return $app['twig']->render('index.html.twig', []);
- })
- ->bind('homepage');
- $blogPosts = [
- 1 => [
- 'date' => '2011-03-29',
- 'author' => 'igorw',
- 'title' => 'Using Silex',
- 'body' => '...It takes time on version changes...',
- ],
- ];
- // Available automatic arguments on controllers: Application, Request.
- $app->get('/blog', function () use ($blogPosts) {
- $output = '';
- foreach ($blogPosts as $post) {
- $output .= $post ['title'];
- $output .= '<br />';
- }
- return $output;
- });
- $app->get('/blog/{id}', function (Application $app, $id) use ($blogPosts) {
- if (!isset ($blogPosts [$id])) {
- $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
- }
- $post = $blogPosts [$id];
- return "<h1>Fifi: {$post['title']}</h1>" . "<p> {$post['body']} </p>";
- })->assert('id', '\d+')
- ->when("request.headers.get('User-Agent') matches '/firefox/i'");
- $app->get('/blog/{id}', function (Application $app, $id) use ($blogPosts) {
- if (!isset ($blogPosts [$id])) {
- $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
- }
- $post = $blogPosts [$id];
- return "<h1> {$post['title']}</h1>" . "<p> {$post['body']} </p>";
- })->assert('id', '\d+');
- $app->post('/feedback', function (Application $app, Request $request) {
- $message = $request->get('message');
- mail($app['app.mail_to'], '[YourSite] Feedback', $message);
- return new Response ('Thank you for your feedback!', Response::HTTP_CREATED);
- });
- $app->get('/user/{user}', function (User $user) {
- return "<h1>User {$user->getId()}</h1>\n";
- })->convert ('user', 'converter.user:convert');
- // Default: http://page, not http://page/
- $app->get ('/page/{pageName}' , function ($pageName) {
- if ($pageName === 'index') {
- return "<p>You requested a default page: ${pageName}.</p>\n";
- }
- else {
- return "<p>Some normal page.</p>\n";
- }
- })->value('pageName', 'index');
- $app->error(function (\Exception $e, Request $request, $code) use ($app) {
- if ($app['debug']) {
- return;
- }
- // 404.html, or 40x.html, or 4xx.html, or error.html
- $templates = array(
- 'errors/'.$code.'.html.twig',
- 'errors/'.substr($code, 0, 2).'x.html.twig',
- 'errors/'.substr($code, 0, 1).'xx.html.twig',
- 'errors/default.html.twig',
- );
- return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
- });
|