在URL中使用破折号时路由不起作用

时间:2012-02-29 21:16:46

标签: php cakephp

我的应用程序中有以下两条路线:

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

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

并且示例网址为:

/posts/This_is_the_first_post-1

但是它会显示404,但是如果我将ID -更改为/之前它会起作用:/任何想法是什么问题?是正则表达式造成的吗?

以下是我的观点方法:

function view ( $id = null, $slug = null )
    {
        $post = $this->Post->find('first',array('contain'=>array('User'=>'Profile'),'conditions'=>array('Post.id'=>$id)));

        if (!$post)
        {
            throw new NotFoundException('404');
        }
        else if($post['Post']['status'] == '0') // 0=draft 1=closed 2=open
        {
            if($post['Post']['user_id'] == $this->Auth->user('id'))
            {
                $this->Session->setFlash('Your post has NOT been published yet');
            }
            else
            {
                throw new NotFoundException('404');
            }
        }

        if (Inflector::slug($post['Post']['title']) != $slug || $slug = null)
        {
            $this->redirect(array('id'=>$post['Post']['id'],'slug'=>Inflector::slug($post['Post']['title'])));
        }

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

1 个答案:

答案 0 :(得分:2)

它看起来是由正则表达式引起的。在第一个路线中,您允许-,因此它可能无法与第二条路线区分开来,其中:id应该跟-

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

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