Is there a way to immediately get the internal path as a string of type controller/action .

I know what can be done like this:

 $internalRoute = Yii::$app->controller->id . '/' . Yii::$app->controller->action->id 

Or so, if in view :

 $internalRoute = $this->context->id . '/' . $this->context->action->id 

But something tells me that you can immediately get the string controller/action ?

  • Isn't it easier for you to write a static function that will output?) - Urmuz Tagizade
  • The Internet podkskazyvaet us that it is possible and so Yii::app()->urlManager->parseUrl(Yii::app()->request) - koks_rs
  • @UrmuzTagizade, did not quite understand what you mean. In general, since I needed an internal path in the template, I just for the time being (as I am still learning :)) defined ( define() ) a constant. - Roman Grinyov
  • @koks_rs, as I understood it, could have been done this way in Yii, and in Yii2 this would not work. - Roman Grinyov

2 answers 2

To get the internal route as a string ( controller/action ) in “any” place of the application, you need to refer to the route property of the class yii\base\Controller :

 Yii::$app->controller->route 

In the controller itself can be accessed as follows:

 $this->route 

And in the presentation like this:

 $this->context->route 

    If used:

     yii\helpers\Url; 

    then you can contact:

     Url::toRoute([]); 

    or

     Url::to([]); 

    and if you want to get the address of the page that is converted for the user, then so:

     Url::to(); 
    • You have an error: if you simply pass an empty array ( [] ), both for toRoute() and for to() , then Undefined offset: 0 pops up. But if you pass an array with one element, for both methods, an empty string ( [''] ) or just an empty string, then the absolute URL (from the root of the site) will return, although the documentation says that it must route (?) .. The to() method when called without arguments also returns a URL. All of the above can be easily verified by defining the rules for urlManager . I need exactly the internal route: controller/action (you can get it as described in my answer). - Roman Grinyov
    • I have a working project with Url::toRoute([]); and Url::to([]); There are no errors, but in general, yes, the method gives a little something not exactly what you need :) - MasterAlex
    • It's strange, of course, that Undefined offset: 0 does not fall out for you, because if you look at the source code , you can see that first (imagine that we passed an empty array) the passed (first) argument is converted to an array: $route = (array) $route; - we get all the same empty array. Then we process the element with the zero index: $route[0] = static::normalizeRoute($route[0]); ... Oops - but there is no element with a zero index. A simplified example: sandbox.onlinephpfunctions.com/code/… . - Roman Grinyov