簡體   English   中英

Symfony2會話>在會話中存儲和檢索數組/項目集合

[英]Symfony2 Sessions > Store & Retrieve array/collection of items in session

我不知道這是否值得提出問題。 我已經閱讀了文檔,但是來自舊PHP $ _SESSION環境,我不確定如何實現。 我有一個測驗類型的應用程序。 在開始測驗時,我想在測驗中獲得所有問題並將其存儲在會話中。 檢索下一個問題時,我要檢查會話中是否存在問題,如果存在,則檢索下一個問題。 我有以下幾點:

public function nextQuestionAction()
{
    $data = $this->getRequest()->request->all();

    $session = new Session();
    $session->start();

    if ($session->has('quiz_questions'))
    {
        $session->get('quiz_questions');
        // Get the next question from the session, 
        // based on the previous question's ID, $data['question_id'];
        // The questions are ordered by an order_index and not by id, but
        // I get the session index based on $data['question_id'] and then 
        // retrieve the next one in line based on the index, or something
        // along that line
        // If there is no next question, then the session must be unset
    }
    else
    {
        $session->create('quiz_questions');

        $quiz = $this->getDoctrine()
        ->getRepository('CriticalReadingQuizBundle:Quiz')
        ->find($data['quiz_id']);

        $questions = $quiz->getQuestions();
        // Store questions in session in such a way that I can retrieve 
        //the next question when this function gets called again.
        //The questions are ordered by an order_index and not by id, but they can
        //be stored in the session in their order with some arbitrary index so that
        //the next in line can be retrieved based on the index of the previous.
    }

    ... // Rest of code returns the fetched question to the front-end.
    // If this is the first time that the function is called, the first question is returned.
    //If there are no questions left (previous fetch fetched the last question), return null.
}

如果有人可以幫助我提供有關在Symfony2中處理會話的代碼,因為這是我第一次與他們合作。 如果需要,我可以發布測驗和問題實體,但是我認為這不是必需的。

您在此處有一個基本的Symfony2會話對象示例: http : //symfony.com/doc/current/book/controller.html#managing-the-session

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM