CakePHP:使用影响因子的友好url,没有id


CakePHP: Friendly urls using inflector and no id

我使用CakePHP建立了一个简单的投资组合,它的url如下:domain.com/portfolio/82/This_is_an_item

我要做的是从url中删除ID。我该怎么做呢?

这是我的视图控制器代码:

function view ( $id, $slug )
{
    $post = $this->Portfolio->read(null, $id));
    $this->set(compact('post'));
}

下面是链接生成器:

<?php echo $this->Html->link($post['Portfolio']['title'],
        array('admin' => false, 'controller' => 'portfolio', 'action' => 'view', $post['Portfolio']['id'], Inflector::slug($post['Portfolio']['title'])),
        array('title' => $post['Portfolio']['title'])); ?>

我猜我需要改变控制器方法来做一些标题上的查找?

任何帮助都将非常感激。由于

我将在数据库中保存该段信息和标题。这样你只需要创建一次。此外,您可能会或可能无法获得一个唯一的链接从段格到标题,所以最好不要尝试。

为了便于处理,您可以使用可打性行为,参见https://gist.github.com/338096(或只是谷歌)。

如果你使用https://gist.github.com/338096(保存为app/model/behaviors中的sluggable.php)中的可打行为,你只需要做几个步骤:

在Profile模型类中添加var $actsAs = array('Sluggable');

var $actsAs = array(
    'Sluggable' => array(
        'fields' => 'title',
        'scope' => false,
        'conditions' => false,
        'slugfield' => 'slug',
        'separator' => '-',
        'overwrite' => false,
        'length' => 256,
        'lower' => true
    )
);

如果你想覆盖设置

在数据库中,在profiles表中增加一个列slug

当您保存一个配置文件时,它会自动添加填充在slug字段中,您不需要采取任何特殊的操作。

可以完全消除id,但必须确保段鼻涕虫是唯一的(指定inUnique验证规则是一个选项)。保存文章时,在"title"字段上使用Inflector::slug()(如果您想保持标题完整,您可能希望将其保存为"slug"字段:

$this->data['Portfolio']['slug'] = Inflector::slug($this->data['Portfolio']['title'])

function view ($slug ){
   $post = $this->Portfolio->find('first', array('conditions'=>array('Portfolio.slug'=>$slug))));
   $this->set(compact('post'));
}

链接:

<?php echo $this->Html->link($post['Portfolio']['title'],
    array('admin' => false, 'controller' => 'portfolio', 'action' => 'view', $post['Portfolio']['slug']),
    array('title' => $post['Portfolio']['title']));