Prettyurl Route Params

In Yii one we could do something like




public class SiteController {


public function actionUser($id)



and then with prettyUrls enabled use a url like /site/user/id/1

But in Yii2 it doesn’t seem to work like that. I can only get it to work like /site/user?id=1

Is this a design decision or am I setting things up incorrectly. I tend to prefer the second url, but it’s not what I was expecting.

The first form should work too but it depends on your config. How did you configure UrlManager, which rules did you add?

Here’s my urlManager setup




'urlManager'=>array(

            'enablePrettyUrl'=>true,

            'showScriptName'=>false,

)



In the documentation it says the following should create /site/page/id/about but it creates /site/page?id=about


echo \Yii::$app->urlManager->createUrl('site/page', ['id' => 'about']);

By the way, will there be a way to define named routes? Or do I always have to know the Controller, the action + the parameters? Compare http://four.laravel.com/docs/routing#named-routes

No named routes. I see no reason to add another layer. Will add more confusion.

@mfrancis107: you have to define a rule that allows parameter to be part of the url path:




    'site/user/id/<id:\d+>' => 'site/user',



@Tropi: I do not see the benefit about giving a name/alias to a route.

When you want to redirect somewhere you say ‘controller/action’ and url will be build from urlmanager rules. This concept is not needed as we already have a fixed schema for routing in yii. Laravel does not have this as far as I see from the docs there.

Let’s take your example from above:




    'site/user/id/<id:\d+>' => 'site/user',



So link to user "tropi" would be: site/user/54083. In code this is:




echo \Yii::$app->urlManager->createUrl('site/user', ['id' => '54803']);



So what if I want to do it like in the forums? Profile URIs here look like: site/user/54083-tropi. If I want to include the username in links (for example for SEO), I have to edit ALL the createUrl() statements instead of just changig one named "profile route".

But I see, it’s not going to come.

Not 100% correct, it would be site/user/id/54083

How would the named "profile route" know the name when in createUrl() it only gets an ID?

You can do this by creating your own UrlRule class that determines users name but I doupt that you want an SQL query each time you create an url.