我有两条或更多条路线将进入同一个控制器和动作。这很好,直到我想在页面上使用帮助器,如表单助手或分页。
会发生什么是当前网址更改为我routes.php
文件中首先声明的内容。
我看到有promote a router with Router::promote的方法但是我不确定我是否可以根据当前使用的网址或路由器或者有更好的方法来做到这一点。
以下是router.php
的示例:
Router::connect('/cars-for-sale/results/*', array('controller' => 'listings', 'action' => 'results'));
Router::connect('/new-cars/results/*', array('controller' => 'listings', 'action' => 'results'));
Router::connect('/used-cars/results/*', array('controller' => 'listings', 'action' => 'results'));
让我们说例如我在网址domain.com/used-cars/results/
并且我正在使用表单助手或分页帮助程序,正在放入操作或href的网址是domain.com/cars-for-sale/results/
。< / p>
任何帮助或信息都将不胜感激。
答案 0 :(得分:2)
这些路线的问题在于,基本上,您创建了重复的网址,这不仅会导致CakePHP选择正确路线的问题,Google也不会这样做;重复的内容将对您的SEO排名产生负面影响!
为了选择正确的URL(Route),CakePHP应该能够根据其参数进行选择;您当前的路线不提供任何区分它们的方法。
你的申请也没有!
所有这些网址都会显示相同的数据;
/cars-for-sale/results/
/new-cars/results/
/used-cars/results/
如果您的申请仅限于这三个类别,最简单的解决方案是创建三个操作,每个类别一个;
控制器:
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)));
}
}
routes.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')
);
如果用于“列表”的网址列表不会被修复并且会展开,那么最好将“过滤器”作为参数传递并将其包含在您的路线中;
routes.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'),
)
);
在您的控制器中:
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'
)
);