gpt4 book ai didi

php - CakePHP 在 URL 中同时使用 Id 和 Title

转载 作者:行者123 更新时间:2023-12-04 06:11:32 25 4
gpt4 key购买 nike

我想创建一个链接,如:/favours/20201/This_is_a_favour使用 id 和赞成标题。

我已经设置了如下链接:

<h3><?php echo $this->Html->link($favour['Favour']['title'], array('controller'=>'favours','action'=>'view',$favour['Favour']['id'], Inflector::slug($favour['Favour']['title']))); ?></h3>

到目前为止, Controller 操作是:
function view ( $id, $title )
{
$favour = $this->Favour->find('first', array(
'conditions' => array('Favour.title' => $title)
));

if (empty($favour))
{
$this->cakeError('error404');
}
$this->set(compact('favour'));
}

Router::connect('/favours/:id/:favourName',array('controller'=>'favours','action'=>'view'),
array(
'favourName'=>'[A-Za-z0-9\._-]+',
'pass'=>array('favourName')
),
array('id' => '[0-9]+')
);

但是我现在得到了 404?

注意:我不想使用 sluggable 插件或将 slugs 存储在数据库中!

最佳答案

首先,您需要在 routes.php 中设置您的路线:

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

Router::connect('/favours/:id/:slug',
array('controller' => 'favors', 'action' => 'view'),
array(
'id' => '[0-9]+',
'slug' => '[A-Za-z0-9\._-]+',
'pass' => array('id', 'slug')
));

然后我建议在您的 Favor 模型中添加一个方法来处理 :slug 的创建。参数,因为您必须从不同的地方使用它,并且您可能希望稍后更改它的工作方式:
public static function slug(array $favour) {
// good enough for now, might want to change this later
return Inflector::slug($favour['title']);
}

然后,每当您创建链接时,请执行以下操作:
array('controller' => 'favours', 'action' => 'view',
'id' => $favour['Favour']['id'], 'slug' => Favour::slug($favour['Favour']))

您的 Controller 操作如下所示:
public function view($id, $slug) {
$favour = $this->Favour->find('first', array('conditions' => array('Favour.id' => $id)));
if (!$favour) {
$this->cakeError('error404');
}
if (Favour::slug($favour['Favour']) != $slug) {
$this->redirect(array('id' => $id, 'slug' => Favour::slug($favour['Favour'])));
}

$this->set(compact('favour'));
}

关于php - CakePHP 在 URL 中同时使用 Id 和 Title,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7718606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com