Veerendra
Veerendra

Reputation: 2622

How to create session in ZF2

Hi i started learning ZF2 a week ago and i am facing some issues in how to work with session in ZF2.

namespace MyApplication\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container; // We need this when using sessions

class UserController extends AbstractActionController {
    public function loginAction() {

        $user_session = new Container('user');
        $user_session->username = 'bravo';
}

    public function welcomeAction() {
        $user_session = new Container('user');
        $username = $user_session->username; // $username now contains 'bravo'
    }
}

Can anyone please help me with the exact code snippet or tell me where i am wrong.

Thanks in advance :)

Upvotes: 0

Views: 79

Answers (1)

user4235231
user4235231

Reputation:

I am also not much familiar to ZF2 but my code may solve the issue you are facing.

class UserController extends AbstractActionController {
    public function loginAction() {
        // Store username in session
        $user_session = new Container('user');
        $user_session->username = 'bravo';

        return $this->redirect()->toRoute('welcome');
    }

The issue was in the function named loginAction you have not redirected after creating the session

Hope it helps you

Upvotes: 1

Related Questions