CakePHP - How to do reverse routing with a bullet?

I am using CakePHP 1.3. I have a product model. Among the database tables there are fields idand slug.

If I have a product id:37and slug:My-Product-TitleI need the product url:

Products / 37 / My-Product-Title

Instead of standard:

products / view / 37

I created a route that looks like this:

Router::connect(
    '/products/:id/:slug',
    array('controller' => 'products', 'action' => 'view'),
    array('pass' => array('id'), 'id' => '[0-9]+')
);

Now I can go on http://server/products/37/My-Product-Title, and he will take me to the right place.

But how do I get reverse routing to automatically create the correct url in $HtmlHelper->link?

When i use:

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

It still outputs the standard products/view/37url.

+5
4

, . - "", .

, - :

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

$slug - slug.

, , MVC:)

Edit:

, . , :

router.php :

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

, /product/ *, /products/ *

:

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

:

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

- . , SEO, .

+5

:

Router::connect(
    '/products/:id/:slug',
    array('controller' => 'products', 'action' => 'view'),
    array('pass' => array('id'), 'id' => '[0-9]+')
);

:

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

( = > ) : param .

+3

, , ProductController:

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);
}

/view/id, /id/slug

Now I can use the default link scheme:

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

and they will be redirected to the correct URL.

The only problem is that I’m not sure how bad it is to redirect every time a user visits the product page?

-1
source

All Articles