Advertisement
thecrypticace

Laravel 4.1 Route Filters

Jan 14th, 2014
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.53 KB | None | 0 0
  1. -- filters.php excerpt --
  2.  
  3. Route::filter('cache', function ($route, $request, $response = null, $cacheLifetime = null) {
  4.     $key = sha1($request->url());
  5.  
  6.     if (is_null($response) and Cache::has($key)) {
  7.         return Cache::get($key);
  8.     }
  9.  
  10.     if (!is_null($response) and !Cache::has($key)) {
  11.  
  12.         if (is_null($cacheLifetime)) {
  13.             $cacheLifetime = 30;
  14.         }
  15.  
  16.         Cache::put($key, $response->getContent(), $cacheLifetime);
  17.     }
  18. });
  19.  
  20. Route::filter('markdown', function ($route, $request, $response = null) {
  21.  
  22.     Clockwork::startEvent('markdown.parse', 'Parsing Markdown');
  23.     $transformedResponse = MarkdownExtra::defaultTransform($response->getContent());
  24.     Clockwork::endEvent('markdown.parse');
  25.  
  26.     $response->setContent($transformedResponse);
  27. });
  28.  
  29. -- routes.php excerpt --
  30.  
  31. Route::get('/markdown-test', function () {
  32.  
  33.     return file_get_contents(app_path() . '/test.md');
  34.  
  35. })->before('cache')->after('markdown|cache:30');
  36.  
  37. -- Result --
  38.  
  39. # Initial Request
  40. 1. Request made
  41. 2. Transformed via Markdown
  42. 3. Stored in Cache
  43. 4. Displayed transformed response
  44.  
  45. # Subsequent Requests
  46. 1. Request made
  47. 2. Returned data retrieved from Cache
  48. 3. Overwritten with content from Route::get closure
  49. 4. Transformed via Markdown
  50. 5. Displayed transformed response
  51. 6. Done
  52.  
  53. -- Expected --
  54.  
  55. # Initial Request
  56. 1. Request made
  57. 2. Transformed via Markdown
  58. 3. Stored in Cache
  59. 4. Displayed transformed response
  60.  
  61. # Subsequent Requests
  62. 1. Request made
  63. 2. Displayed data retrieved from Cache
  64. 3. Done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement