Search code examples
phpsymfonysymfony-routingsymfony-components

Map the router placeholder with the URI values


I don't how to explain this so please be easy on me.

The router holds the uri variable key

$router = 'movie/english/{slug}/edit/(id}/{title}';

The URI in the browser address bar

$uri = 'movie/english/scorpion/edit/125/E01E05';

How can I write the code that will map the router placeholder variable with the URI matching value. E.g.

array(
    'slug' => 'scorpion',
    'id' => '125',
    'title' => 'E01E05'
);

Please if you understand can you redirect me to the correct resource.


Solution

  • You can write custom solution for this, but you will reveal wheel every time when you will need something more, that's why my advice use the best practice:

    composer require symfony/routing

    <?php
    
    require './vendor/autoload.php';
    
    use Symfony\Component\Routing\Matcher\UrlMatcher;
    use Symfony\Component\Routing\RequestContext;
    use Symfony\Component\Routing\Route;
    use Symfony\Component\Routing\RouteCollection;
    
    $route = new Route(
        '/movie/english/{slug}/edit/{id}/{title}',
        array('controller' => 'MyController')
    );
    $routes = new RouteCollection();
    $routes->add('route_name', $route);
    
    $context = new RequestContext();
    $matcher = new UrlMatcher($routes, $context);
    $parameters = $matcher->match('/movie/english/scorpion/edit/125/E01E05');
    
    var_dump($parameters);
    

    will print:

    array (size=5)
      'controller' => string 'MyController' (length=12)
      'slug' => string 'scorpion' (length=8)
      'id' => string '125' (length=3)
      'title' => string 'E01E05' (length=6)
      '_route' => string 'route_name' (length=10)
    

    I truly believe that it's the best solution, hope it'll help you.