silex,php中缺少变量


Missing variable in silex, php

我们正在Silex中创建博客,变量$posts_id有问题。在我们尝试在$data中使用它之后,无论它以前的值如何,它总是int 0。我们无法生成下一个页面,它将是带有所有可见评论的帖子页面视图,变量posts_id与帖子id匹配。以下是我们的功能:

public function addAction(Application $app, Request $request)
{
    $posts_id = (int)$request->get('posts_id');
    $data = array(
        'comment' => 'Comment',
        'date' => date('Y-m-d H:m:s'),
        'posts_id' => $posts_id
    );
    $form = $app['form.factory']
        ->createBuilder(new CommentForm(), $data)->getForm();
    $form->handleRequest($request);
    if ($form->isValid()) {
        $data = $form->getData();
        $model = $this->_model->addComment($data);
        return $app->redirect(
            $app['url_generator']->generate(
                'posts_view', array('id' => $data['posts_id'])
            ), 301
        );
    }
    $this->_view['form'] = $form->createView();
    $app['session']->getFlashBag()->add(
        'message', array(
            'type' => 'success', 'content' => $app['translator']->trans('New comment added.')
        )
    );
    return $app['twig']->render(
        'comments/add.twig', array(
            'form' => $form->createView(),
            'posts_id' => $posts_id
        )
    );
}

public function addComment($data)
{
    $sql = 'INSERT INTO comments
    (comment, date, posts_id)
    VALUES (?,?,?)';
    $this->_db
        ->executeQuery(
            $sql,
            array(
                $data['comment'],
                $data['date'],
                $data['posts_id']
            )
        );
}

}

函数内的变量不是全局变量,这意味着您需要在addComment()函数内再次实例化Request

public function addComment($data, Request $request)
{
    $posts_id = (int)$request->get('posts_id');
    $sql = 'INSERT INTO comments
    (comment, date, posts_id)
    VALUES (?,?,?)';
    $this->_db
        ->executeQuery(
            $sql,
            array(
                $data['comment'],
                $data['date'],
                $data['posts_id']
            )
        );
}