A
A
Artur Kosikov2017-10-18 12:58:32
Yii
Artur Kosikov, 2017-10-18 12:58:32

How to correctly make a rule for UrlManager in Yii2?

There is a table of cities in b.d. in the format
city_id, city_name, city_slug
There are a lot of cities. I'm making a bulletin board. I want the following URL structure:
site.ru/city/category
i.e. the first parameter is city_slug.
Solved the issue like this:

'<city>/<category>/<page:\d+>' => 'main/index',
'<city>/<category>' => 'main/index',
'<city>' => 'main/index',
''=>'main/index',

Now the first parameter in the URL is always the city. And you have to write rule above this code for absolutely all other controllers / actions.
There is such a solution:
<city:(moskva|spb|samara ... )>
but enter the entire list of cities here? There are several thousand of them. And they should be taken from the database.
In general, the meaning of the problem: you need to look at the first parameter in the URL, and look for it in the table (city_slug field). If there is one - send a request to the appropriate controller, if not - ignore ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-10-18
@qonand

Create your own rule class that will perform the logic you need and use it

M
Maxim Timofeev, 2017-10-18
@webinar

Now the first parameter in the URL is always considered the city

And why is it bad? I understand that this is exactly what you need. If there are urls like page/somepage/, just put their rules before the city rules. It turns out that if all the rules did not work, then the first parameter is the url. UrlManager simply goes through the array of rules and when it finds a suitable one, it doesn’t go further, so changing the order can quite achieve the desired result. Or a more complex option suggested by Maxim Fedorov

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question