CakePHP - How to do reverse routing with slug?

前端 未结 4 1137
囚心锁ツ
囚心锁ツ 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:46

    I am not sure how bad this is but with the following code in the ProductsController:

    function view($id)
    {
        if( isset($_SERVER) && stristr($_SERVER["REQUEST_URI"],'view/') )
        {
            $this->Product->id = $id;
            $slug = $this->Product->field('slug');
            $this->redirect($id.'/'.$slug);
        }
        $data = $this->Product->find('first', array('conditions' => array('Product.id' => $id)));
        $this->set("data", $data);
    }
    

    If the page is accesses via /view/id it automatically redirects them to the current page using /id/slug

    Now I can just use the default link scheme:

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

    and they will be redirected to the right URL.

    Only problem is I am not sure how bad it is to have a redirect happening every time a user visits a product page?

提交回复
热议问题