How to use zf3-way to get sessonid? I operate session like "$sessionContainer = new Container('api');"


#1

In my zf3 model, I use the following way to operate my session stuff.
$sessionContainer = new Container(‘api’);

Now I need to get sessionid in my logic, if use the pure php, it will like:
$sessionId = session_id();

I wonder if there is a zf3-official way to get sessionid.

Thanks!


#2

Do you create a zend-mvc based application?


#3

yes! :slightly_smiling_face: :slightly_smiling_face:


#4

Here is the standard way of using zend-session within a zend-mvc-based application:

  1. install zend-session per Composer

  2. enable zend-session as module

config/modules.config.php:

return [
    'Zend\Router',
    'Zend\Session', // <-- Add this line
    'Zend\Validator',
    'Application',
];
  1. extend the conifguration

config/autoload/global.config.php:

return [
    // ...
    'session_config'  => [],
    'session_storage' => [
        'type' => Zend\Session\Storage\SessionArrayStorage::class,
    ],
];
  1. add the session-manager to the controller

module/Application/src/Controller/IndexController.php:

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\SessionManager;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    /**
     * @var SessionManager
     */
    private $sessionManager;

    public function __construct(SessionManager $sessionManager)
    {
        $this->sessionManager = $sessionManager;
    }

    // ...
}
  1. update the controller configuration

module/Application/config/module.config.php:

return [
    'controllers'  => [
        'factories' => [
            Controller\IndexController::class => \Zend\ServiceManager\AbstractFactory\ReflectionBasedAbstractFactory::class,
        ],
    ],
    // ...
];
  1. use the session-manager

module/Application/src/Controller/IndexController.php:

    public function indexAction()
    {
        var_dump($this->sessionManager->getId());

        return new ViewModel();
    }

(The example is based on the zend-skeletion-application.)

The configuration is documented at: https://docs.zendframework.com/zend-session/config/
The session-manager is described at: https://docs.zendframework.com/zend-session/manager/

And you can get the session-id also with PHP’s standard function session_id. Nothing else is done in the session-manager: https://github.com/zendframework/zend-session/blob/2cfd90e1a2f6b066b9f908599251d8f64f07021b/src/SessionManager.php#L309-L319


#5

Hi Froschdesign, thank you so much!

$this->sessionManager->getId(); It is the right zf3 way solution!

I will use your way to improve my image drag auth plugin as I asked with topic how to get $container in static method. I saw you kindly answer me as well. thank you again.