Dynamic entry in UrlManager

Here is my situation:

I have a ‘categories’ table that has the columns ( id, title, slug, parentid ).

I want my url struture to be something like this:

/<category slug>/action

Is it possible with Yii to have the category slug be a rule in the UrlManager. I can’t seem to think of a way to do this in order to have createUrl() still be usable.

Right now I am catching all errors, checking if it is a 404, splitting up the URI and parsing the different sections. This works fine for me but I want to also be able to use createUrl() so that the urls that yii spits out will use the url setup I have designed.

As of now I have controllers for items like: "blogs, videos, podcasts, articles" and I can access items that belong to a category like:

‘/blogs/12/category-slug’ where ‘12’ is the categoryId.

But the end result I want to achieve is more like:


If anyone could give me some pointers it would be greatly appreciated. I am sure others have tried this but it would be nice to have a reference to what people think is the "correct" way to achieve the desired results.

Thanks in advance

Where’s the problem? <slug> can be used just like a standard URL parameter. So when creating your URL, you supply the slug for the URL to generate. You should maybe make sure, that ‘/’ are replaced with e.g. ‘_’ before.


If you want to leave away the ID, you can do so, but then you have to make sure, your slugs are unique and normalized.

If you didn’t solve the problem yet, try the extension dburlmanager. It was made for that.

I have these rules in my config:



which allows me to have www.myblog.org/a_slug_here and www.myblog.org/page/another_slug

I have a function to load my model by slug, in addition to the ‘standard’ one which loads it by id.

It works. ;)

Just make sure that you’re passing the slug as a parameter so that Yii can rewrite the url.

jacmoe, sure it works and is a valid strategy.

What dburlmanager gives you is that it checks the db for the slug. If the slug is not there, it doesn’t allow Yii URL Manager to match the route.

It allows you to have multiple parameters (slug, category etc), each one sent to its specific route and makes it compatible with standard routes.

Just my 2 cents :)

Yes, it’s pretty neat. :)

But since my requirements are pretty simple, I did not use it for my project, thus avoiding the (small) overhead.

It’s definitely a great help for more complex/dynamic rules, so if you find that the urlManager config section grows too big, that extension is going to save you.

You’re right, your config fits your case.

And you are very kind, but the overhead shouldn’t be so small. Depending on the rules configuration, it could add at least one query for each request. I will implement caching when I have some time.