CakePHP - How to do reverse routing with slug?

前端 未结 4 1124
囚心锁ツ
囚心锁ツ 2021-01-13 12:12

I am using CakePHP 1.3. I have a Product model. on the DB table among others there are id and slug fields.

If I have a product that is

4条回答
  •  粉色の甜心
    2021-01-13 12:47

    I don't believe that it's possible to be done auto-magically. The helper is just an "helper" who builds the link from the given parameters.

    So the easiest method is to add another parameter in your link like so:

    echo $html->link(
        'Product 37', 
        array('controller'=>'products', 'action' => 'view', 37, $slug)
    );
    

    where the $slug is the data from the slug field.

    Probably it could be done your idea, but you need to break the MVC pattern very badly :)

    Edit:

    Reading your question again I understood it well. See how should be done:

    in your router.php add the following rule:

    Router::connect(
        '/product/*',
        array('controller' => 'products', 'action' => 'view')
    );
    

    Please note that it's /product/* rather than /products/*

    Your link should be done like this:

    echo $html->link(
        'Product 37', 
        array('controller'=>'products', 'action' => 'view', 37, 'my-product-title')
    );
    

    and the link would look like:

    http://yourdomain.com/product/37/my-product-title
    

    For me doing your suggestion is bad practice. Also I don't think it's good from SEO point of view redirecting always the user.

提交回复
热议问题