Advertisement
SZoPer

Symfony Routing Compony example

Nov 4th, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.97 KB | None | 0 0
  1. <?php
  2. /**
  3.  * @author Tomasz Marcinkowski
  4.  * @since 31 10 2013
  5.  */
  6.  
  7. $path_base = '/symfony-components';
  8.  
  9. spl_autoload_register(function ($class) {
  10.   $pcr0_class_to_path = str_replace('\\', '/', $class);
  11.   require __DIR__ . '/' . $pcr0_class_to_path . '.php';
  12. });
  13.  
  14. ini_set('display_errors', 1);
  15. error_reporting(E_ALL);
  16.  
  17. use Symfony\Component\Routing\Generator\UrlGenerator;
  18. use Symfony\Component\Routing\Matcher\UrlMatcher;
  19. use Symfony\Component\Routing\RequestContext;
  20. use Symfony\Component\Routing\RouteCollection;
  21. use Symfony\Component\Routing\Route;
  22.  
  23. $routes = new RouteCollection();
  24. $routes->addPrefix($path_base);
  25. $routes->setHost('{subdomain}{_dot}szoper.net');
  26. $routes->addRequirements(array(
  27.   'subdomain'  => '[a-z-]*',
  28.   '_dot'=>'\.?',
  29. ));
  30. $routes->addDefaults(array('slash' => '/'));
  31.  
  32. $routes->add('homepage', new Route('{slash}', array('controller' => 'HomepageController'), array(
  33.   'slash' => '/*',
  34. )));
  35. $routes->add('products', new Route(
  36.   '/product/{product_id}',
  37.   array('controller' => 'ProductController'),
  38.   array(
  39.     'product_id' => '[0-9]*',
  40.   )
  41. ));
  42. $routes->add('posts', new Route(
  43.   '/post/{post_id}',
  44.   array('controller' => 'PostController'),
  45.   array(
  46.     'post_id' => '[0-9]*',
  47.     'subdomain'  => '[a-z-]*',
  48.     '_dot'=>'\.?',
  49.   ),
  50.   array(),
  51.   '{subdomain}{_dot}szoper.net'
  52. ));
  53.  
  54. $context = new RequestContext('', $_SERVER['REQUEST_METHOD'], $_SERVER['HTTP_HOST']);
  55. $matcher = new UrlMatcher($routes, $context);
  56. $generator = new UrlGenerator($routes, $context);
  57.  
  58. $path_info = preg_replace('!^' . $path_base . '!', '', $_SERVER['REQUEST_URI']);
  59.  
  60. try {
  61.   $parameters = $matcher->match($path_info);
  62.   var_dump($parameters);
  63. } catch (\Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  64.   printf('oops! no controller found for: %s', $path_info);
  65. }
  66.  
  67.  
  68. $link = $generator->generate('products', array('product_id' => rand(1,999)), true);
  69. echo sprintf('<br>Random product link: <a href="%s">%s</a>', $link, $link);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement