1

Is there any way to get the controller name and action name using a given uri?

Example:

uri: http://test/client/edit/48

Controller name => client Action name => edit

akond
  • 15,865
  • 4
  • 35
  • 55
user2117289
  • 11
  • 1
  • 2
  • it's impossible to do via the actual URL string if that's what you are asking? This is because you can have any URL you want with any amount of segments depending on your Route config. You should use the method blow using RouteMatch :) – Andrew Feb 28 '13 at 08:22

3 Answers3

11

You can match your uri against the application router to get a RouteMatch object.

$request = new \Zend\Http\Request();
$request->setUri($uri);
$router = $serviceLocator->get('Router');
$routeMatch = $router->match($request);

Now you can retrieve your params.

if ($routeMatch) {
    $controller = $routeMatch->getParam('controller');
    $action     = $routeMatch->getParam('action');
}
Bram Gerritsen
  • 7,178
  • 4
  • 35
  • 45
  • First, thanks for the answer! The problema is that to use the match procedure, we need a Zend\Stdlib\RequestInterface. How can we build a object that implements this interface using a given uri? – user2117289 Mar 01 '13 at 17:49
  • You can use the `\Zend\Http\Request` class. I have edited my answer. Let me know if it works. – Bram Gerritsen Mar 02 '13 at 00:35
1

In your controller add these:-

use Zend\Stdlib\RequestInterface as Request;
use Zend\Stdlib\ResponseInterface as Response;

Then create a dispatch function in your controller

public function dispatch(Request $request, Response $response = null)
{
    $controller = $this->params('controller');
    $action = $this->params('action');

    echo "Controller: " . $controller . " Action: " . $action;
}
deadtoy
  • 43
  • 4
0

Though late, but to help new visitors, resolved ans here,

ZF2: Get url parameters in controller

in short, this code should help,

$controller = $this->params()->fromRoute('RouteParamForController');
Community
  • 1
  • 1
Nishchith Uchil
  • 152
  • 1
  • 14