5

We want to mask specific action routes in our project's routes.php file. Currently what we have looks like this:

return array(
    // /actions/api/element/section/name/{$name}/
    'api/test/(?P<name>)'  => ['action' => 'api/element/section'],
);

We would like to pass name into the action array somehow. Is there something documented or undocumented that I'm missing? Or is what I'm attempting not possible at this time?

5

Yes it’s possible. First you will need to update your route key so that you’re capturing the name parameter with a valid named subpattern. (You were close, but missing the actual pattern part of it).

return array(
    'api/test/(?P<name>[^\/]+)' => ['action' => 'api/element/section'],
);

Any named subpattern matches in your route will be passed to your controller action’s $variables argument, if it has one.

class Api_ElementController extends BaseController
{
    // ...

    public function actionSection(array $variables = array())
    {
        $name = $variables['name'];

        // ...
    }
}

Note that you specifically need to call the argument “$variables”, and you need to typeset it to an array for this to work.

  • Does it look to you like I'm doing something wrong with the regex to get the name? Right now I'm not getting to the actionSection method. I put a commented out version of the original in my question. – Tyler Willingham Jul 11 '14 at 20:24
  • I’m not sure what that means - is the code above your route or not? – Brandon Kelly Jul 11 '14 at 20:32
  • Before implementing your change, hitting /actions/api/element/section/name/triviaQuestions/ will trigger actionSection($name) with $name='triviaQuestions'. However if I use the above route (/api/test/triviaQuestions) I get a 404 - leading me to believe I've done something wrong in my routing. – Tyler Willingham Jul 11 '14 at 20:38
  • @TylerWillingham Ah, there is a bug in your route. Just updated my answer. – Brandon Kelly Jul 11 '14 at 21:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.