silex 中缺少变量,php

Missing variable in silex, php

我们正在 Silex 中创建博客,我们遇到了变量 $posts_id 的问题。在我们尝试在 $data 中使用它之后,无论其先前的值如何,它始终为 int 0。我们无法生成下一页,这将是 post 页面的视图,其中包含所有可见评论,变量 posts_id 匹配 ID post。 这是我们的功能:

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']
            )
        );
}