路线应该是唯一且可识别的!
这些路由的问题在于,基本上,您创建了重复的 URL,这不仅会导致 CakePHP 选择正确的路由出现问题,而且 Google 也不喜欢这样;重复的内容会对您的 SEO 排名产生负面影响!
为了选择正确的 URL(路由),CakePHP 应该能够根据其参数这样做;您当前的路线不提供任何区分它们的方法。
你的应用程序也没有!
所有这些 URL 都将呈现相同的数据;
/cars-for-sale/results/
/new-cars/results/
/used-cars/results/
解决方案 1 - 单独的操作
如果您的应用程序仅限于这三个类别,最简单的解决方案是创建三个操作,每个类别一个;
控制器:
class ListingsController extends AppController
{
const CATEGORY_NEW = 1;
const CATEGORY_USED = 2;
const CATEGORY_FOR_SALE = 3;
public $uses = array('Car');
public function forSaleCars()
{
$this->set('cars', $this->Paginator->paginate('Car', array('Car.category_id' => self::CATEGORY_FOR_SALE)));
}
public function newCars()
{
$this->set('cars', $this->Paginator->paginate('Car', array('Car.category_id' => self::CATEGORY_NEW)));
}
public function usedCars()
{
$this->set('cars', $this->Paginator->paginate('Car', array('Car.category_id' => self::CATEGORY_USED)));
}
}
路由.php
Router::connect(
'/cars-for-sale/results/*',
array('controller' => 'listings', 'action' => 'forSaleCars')
);
Router::connect(
'/new-cars/results/*',
array('controller' => 'listings', 'action' => 'newCars')
);
Router::connect(
'/used-cars/results/*',
array('controller' => 'listings', 'action' => 'usedCars')
);
解决方案 2 - 将“类别”作为参数传递
如果用于“列表”的 URL 列表不会固定并会扩展,最好将“过滤器”作为参数传递并将其包含在您的路由中;
路由.php
Router::connect(
'/:category/results/*',
array(
'controller' => 'listings',
'action' => 'results',
),
array(
// category: lowercase alphanumeric and dashes, but NO leading/trailing dash
'category' => '[a-z0-9]{1}([a-z0-9\-]{2,}[a-z0-9]{1})?',
// Mark category as 'persistent' so that the Html/PaginatorHelper
// will automatically use the current category to generate links
'persist' => array('category'),
// pass the category as parameter for the 'results' action
'pass' => array('category'),
)
);
阅读路由器 API
在您的控制器中:
class ListingsController extends AppController
{
public $uses = array('Car');
/**
* Shows results for the specified category
*
* @param string $category
*
* @throws NotFoundException
*/
public function results($category = null)
{
$categoryId = $this->Car->Category->field('id', array('name' => $category));
if (!$categoryId) {
throw new NotFoundException(__('Unknown category'));
}
$this->set('cars', $this->Paginator->paginate('Car', array('Car.category_id' => $categoryId)));
}
}
并且,创建指向某个类别的链接;
$this->Html->link('New Cars',
array(
'controller' => 'listings',
'action' => 'results',
'category' => 'new-cars'
)
);