Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 3 - route based on query string

In Zend Framework 3, is it possible to route to a controller depending on whether a URL contains a query string?

For example, I have these two URLs:

/users
/users?name=Bob

I would like the first route to call a UsersController and second route to call a NameController.

Is this possible?

like image 711
Leo Galleguillos Avatar asked Feb 04 '26 19:02

Leo Galleguillos


1 Answers

Have a read of the ZF3 docs on Router and possibly RFC 3986 Chapter 3 - Syntax Components which shows what is path and what is query.

From RFC 3986 Chapter 3 - Syntax Components

The following are two example URIs and their component parts:

     foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \
     urn:example:animal:ferret:nose

ZF3 route configuration is typically configuration on a path. (This is also true of pretty much every common framework.) Yes, variables can be part of a path. As such, they're configured in route configuration. Advanced configuration of framework routing often also allows for changes/requirements in schemes and authorities.

Not part of routing configurations are the 'query' and 'fragment' parts.

If you want to do something, e.g. catch a "name" key/value pair and do routing accordingly, you're going to have to create a "catcher" (or whatever the name for that would be) on the path and determine the redirection yourself.

For example, you could do something like this answer. If your controller instance extends the default Zend Framework AbstractActionController class, then you should have the forward plugin available. From the docs:

Forward returns the results of dispatching the requested controller; it is up to the developer to determine what, if anything, to do with those results. One recommendation is to aggregate them in any return value from the invoking controller.

As an example:

 $foo = $this->forward()->dispatch('foo', ['action' => 'process']);
 return [
     'somekey' => $somevalue,
     'foo'     => $foo,
 ];

Of course, you could immediately return it.

Another option is the redirect plugin (same link).

return $this->redirect()->toRoute('login-success');

With all this you can do something like:

$name = $this->params()->fromQuery('name', null);

if ($name) {
    // dispatch

    if ($dispatchResult) {
        // return special
    }
} 

// redirect

Where you redirect to a route name (ie. configured path)

like image 189
rkeet Avatar answered Feb 06 '26 09:02

rkeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!