Answer the question
In order to leave comments, you need to log in
How to make routing in Yii2 correctly if categories start from the main page?
Hello.
There is a site. Categories start from the site root. For example:
site.ru/category1/
site.ru/category1/category2/
How to properly configure links with categories to be processed, for example, in the catalog/category controller. Links will be in Russian letters.
I tried through routing, it did not work, because there is no experience in yii2. I even tried it through .htaccess, it didn't work either.
Answer the question
In order to leave comments, you need to log in
You need to write your own urlManager, but why such a url? Url should be as short and flexible as possible. If you need to show the nesting of categories, there are breadcrumbs.
With your approach, element 2 is the name of the category, that is, making a section of the site, let's say "news", will no longer work. Or it is necessary to fence a heap of checks and exceptions.
Honestly, I have not worked with YII, but I would probably do it this way.
urls table in this table we store url slugs, and only the one that is the last segment in the address, that is, if the address site.ru/category1/category2/ is such, then "category2" will be written in the slug The
table will contain the columns id, pageable_id, pageable_type , slud
Polymorphic association
pageable_type is the object's short identifier or its full namespace path
pageable_id is the id of the product, category, page, or whatever you need to process.
We create a controller that processes all addresses in a row, except for those that are registered in the routes
The controller receives the full URI and takes its last segment, looks in the Url model by slug, if nothing is found 404 otherwise we move on.
Categories need to be done through a nestedset, so we have a category for the last segment, get all the parents and build a new URI, compare it with the one we are currently on, if it doesn’t match, then redirect to the one that we generated ourselves, this is necessary so that there is no access to the same page at different addresses.
but I’ll warn you right away, such a scheme will work only when categories can have only one parent
. Otherwise, it’s better to do it without nesting
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question