Dynamic routing in CakePHP
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!
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)));
...
}
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'];
}
}
精彩评论