2012-07-17 115 views

回答

-1

短的片段來設置會話

$session = $this->getRequest()->getSession(); 
$session->set('name', 'Sensorario'); 

某個值,並且非常非常簡單的例子來得到這個值

echo $session->get('name'); 
+0

不起作用...我必須手動創建請求變量,因爲它來自CLI – greg 2012-07-17 00:36:08

+0

測試中沒有$ this-> getRequest()。在執行任何請求之前,$ this - > $ client-> getRequest()在null中。所以,它不會工作 – 2017-10-02 13:14:17

1

您應該使用WebTestCase

然後你可以做類似問題的回答中描述的事情:how-can-i-persist-data-with-symfony2s-session-service-during-a-functional-test

所以像:

$client = static::createClient(); 
$container = $client->getContainer(); 
$session = $container->get('session'); 
$session->set('name', 'Sensorario'); 
$session->save(); 
+0

感謝您的迴應,我已經試過,並閱讀該文章,但我仍然得到這個:'致命的錯誤:調用一個非對象的成員函數getContainer()' – greg 2012-07-17 17:06:26

+0

做你的測試類擴展這一個https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php? – l3l0 2012-07-17 19:13:05

0

如果使用WebTestCase,您可以檢索 「會話」 的服務。 有了這項服務,您可以:

  • 啓動會話,
  • 設置一些參數到會話,
  • 保存會話,
  • 通過Cookie的使用的sessionId請求

該代碼可以是以下代碼:

use Symfony\Component\BrowserKit\Cookie; 
.... 
.... 
public function testARequestWithSession() 
{ 
    $client = static::createClient(); 
    $session = $client->getContainer()->get('session'); 
    $session->start(); // optional because the ->set() method do the start 
    $session->set('my_session_variable', 'myvar'); // the session is started here if you do not use the ->start() method 
    $session->save(); // important if you want to persist the params 
    $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId())); // important if you want that the request retrieve the session 

    $client->request(.... ...