How can I use a URL to read out the controller, action and any other parameters?


I’m currently building a helper class for my menu. It is important that I know whether the page I clicked on in the menu is the right one. Because if so, I can then add a css class.

I have a menu pointing to http://localhost/shop/view/1. Now I would like to read out the controller, the action and, if necessary, all other parameters. I also have some zsm. tinkered, but that doesn’t work. Can someone help me there? :slight_smile:

use Cake\Http\ServerRequest;
use Cake\View\Helper;
use Cake\Routing\Router;

public function isCurentActive( $url ) {
		$request = new ServerRequest( array('url' => $url) );
		$route   = Router::parseRequest( $request );
		$controller = $route['controller'];
		$action     = $route['action'];
		$request           = Router::getRequest();
		$actualController = $request->getParam( 'controller' );
		$actualAction     = $request->getParam( 'action' );
		$actualPassedArgs        = $request->getParam( 'pass' );
		return ($actualController === $controller) && ($actualAction === $action);

What is not working about this? What sort of data are you passing into this for the $url (string or array), and if a string, why?

Hello @Zuluru :slight_smile:

The URL parameter is a string. And looks something like this: “http://localhost/shop/view/1” The URLs are stored in a database and are output as a <ul><li> list in a loop. This is how the menu is created.

Now I have to check if the link I saved in the database matches the currently visited page.

Currently I get the following error message:

Missing Route

See the screenshot

There’s a “/” at the beginning of the URL it’s trying to match: “/http…”. I’m not familiar with what Router::parseRequest does, but maybe it’s expecting just a URL fragment, not the entire thing with domain name included?

// URL should be without protocol and domain name
$route = Router::getRouteCollection()->parse('/shop/view/1');

Thank you :slight_smile: I managed it with the help of you. Thanks very much :slight_smile: