Reputation: 2498
I'm trying to set dynamic routes for small CMS. Is there proper way how to do it? I founded somewhere this soliution, but honestly I'm not satisfied with it. CMS have other content types so define this for every model does't seem right to me.
$productsModel = ClassRegistry::init('Product');
$products = $productsModel->find('all');
foreach($products as $product){
Router::connect('/produkty/:id/'.$product['Product']['url'], array('controller' => 'products', 'action' => 'view',$product['Product']['id']));
}
Thanks for any help!
Upvotes: 3
Views: 5702
Reputation: 543
Yop,
You don't need to define route for each entry in your model DB. Routes ARE dynamics. There are many ways to define routes but the easier is to pass args to action like they comes.
routes.php
Router::connect('/produkty/*', array('controller' => 'products', 'action' => 'view'));
products_controller.php
class ProductsController extends AppController{
public function view($id){
//do anything you want with your product id
}
}
You can also use named args
routes.php
Router::connect('/produkty/:id/*', array('controller' => 'products', 'action' => 'view'), array('id' => '[0-9]+'));
products_controller.php
class ProductsController extends AppController{
public function view(){
//named args can be find at $this->params['named']
$productId = $this->params['named']['id'];
}
}
Upvotes: 2
Reputation: 2126
No need to do anything complex :)
In routes.php:
Router::connect('/produkty/*', array('controller'=>'products', 'action'=>'view'));
In products_controller.php:
function view($url = null) {
$product = $this->Product->find('first', array('conditions'=>array('Product.url' => $url)));
...
}
Upvotes: 2