We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Get param value on beforeMatch()

Hi! Is there anyway to get a value from a route param inside the beforeMatch callback???

something like:


    <?php

    $router->add( '/:module/([a-zA-Z]+)', array(
      'module'     => 1,
      'controller'  => 'multi-model',
      'model'       => 2
    ))
    ->beforeMatch( function( $uri, $route ){
        // i need the value of 'model' param
        $model = $route->getParam('model');

        if( !in_array( $model, $allowedModels ) )
            return false;

        return true;
    });

I need this, because if the model is not in the allowedModels array the route will be treated as non-matched, then, the route can find new matches.

thanks!



98.9k

I'm not sure if a beforeMatch is the best place to put that logic. You can better implement a notFound handler and then perform a forward to the right action.



36.8k

I'm not sure if a beforeMatch is the best place to put that logic. You can better implement a notFound handler and then perform a forward to the right action.

Thanks @Phalcon

ammmm.... i don't think it works for me, i have another route like:


  $router->add( '/:module/:controller', array(
    'module'     => 1,
    'controller' => 2
  ))

  $router->add( '/:module/([a-zA-Z]+)', array(
    'module'     => 1,
    'controller'  => 'multi-model',
    'model'       => 2
  ))
  ->beforeMatch( function( $uri, $route ){
      // i need the value of 'model' param
      $model = $route->getParam('model');

      if( !in_array( $model, $allowedModels ) )
          return false;

      return true;
    });

this route matches too with a uri like /admin/user, then, notFound handler doesn't works.

The solution for that, i think, its put the notFound handler on the dispatcher, but this doesn't works too, because i need the value of 'model' param.

Any suggestions??



98.9k

But, logic like that could be placed in a beforeExecuteRoute/beforeDispatch:

If a user does not have access to an allowed model you can forward it to another action.