使用帖子标题作为url的CakePHP视图方法


CakePHP view method using post title as url

我的投资组合有以下链接结构:

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

它给出的URL如下:http://driz.co.uk/portfolio/view/Paperview_Magazine

但是,我如何让我的控制器根据标题显示项目?

到目前为止,我有这个,但还没能让它发挥作用,只得到了一个空白页(所以我还需要检查格式是否正确,以及它们是否是相关项目)

function view ( $title )
{
    $posts = $this->Portfolio->find('first', array('conditions' => array('Portfolio.title' => $title)
    ));
    if (empty($title))
    {
        $this->cakeError('error404');
    }
    $this->set(compact('posts'));
}

@Ross建议您使用Portfolio.slug进行搜索,以下是您可以做到的方法:

  1. 在数据库表中添加一个名为slug的字段。你很可能想要一个足够长的VARCHAR来容纳子弹
  2. 创建或更新"Portfolio"记录时,使用Inflector::slug方法生成一个slug并将其保存到数据库中。您可以在模型的beforeSave事件中执行此操作,或者如果您愿意,在保存数据之前在控制器中执行
  3. 更新find调用以查找Portfolio.slug而不是Portfolio.title

不幸的是,没有办法逆转Inflector::Slug函数,因为它删除了某些字符,如撇号、引号、括号等。这就是为什么如果你想搜索它,你需要将Slug保存到数据库中。

以下是如何在模型中使用beforeSave事件:

public function beforeSave(array $options = array())
{
  // If the title is not empty, create/update the slug.
  if ( ! empty($this->data[$this->alias]['title'] )
    $this->data[$this->alias]['slug'] = Inflector::slug($this->data[$this->alias]['title']);
  // Returning true is important otherwise the save or saveAll call will fail.
  return true;
}