0
votes

I've two modules Application and Manager. Application module has AuthStorage service and i'm using a container to store the userlevel(admin or user).

But when accessing the container in Application\Model\AuthStorage from Manager module, the container seems to be empty.

Is it creating a new instance when called from another module? (It looks like so).

Is the scope of AuthStorage service instance limited to Application module?

Or How can I access the userlevel container globally?

Here is how I access the storage service from Manager module:

$this->storage = $this->getServiceLocator()
                              ->get('Application\Model\AuthStorage');

Module.php getServiceConfig()

'factories'=>array(
            'Application\Model\AuthStorage' => function($sm){
                return new \Application\Model\AuthStorage('db');
            },

AuthStorage class

namespace Application\Model;

use Zend\Authentication\Storage;
use Zend\Session\Container;

class AuthStorage extends Storage\Session
{
    protected $container;

    public function setRememberMe($rememberMe = 0, $time = 1209600)
    {
         if ($rememberMe == 1) {
             $this->session->getManager()->rememberMe($time);
         }
    }

    public function forgetMe()
    {
        $this->session->getManager()->forgetMe();
    }

    public function getContainer()
    {
        if (!isset($this->container)) {
            $this->container  = new Container('authsessionstorage');
            $this->container->userlevel = 0;
        }
        return $this->container;
    }

    public function setUserLevel($userlevel)
    {
        $_container = $this->getContainer();
        $_container->userlevel = $userlevel;
    }

    public function getUserLevel()
    {
        $_container = $this->getContainer();
        return $_container->userlevel;
    }

    public function isAdministrator() {
        echo '<pre>', 'userlevel = ' . print_r($this->getUserLevel(), true), '</pre>';
        if ($this->getUserLevel() == 100) {
            return true;
        }
        return false;
    }
}
1
You will need to show the code for AuthStorage before anyone can answer your question properly. - AlexP
Updated now. The same container code works fine within Application Module(in AuthController), but not from Manager module's ManagerController. - Bala

1 Answers

0
votes

Zend\Session\Container is simply an interface for working with PHP $_SESSION so it is not module specific in ZF2.

This line;

$this->container  = new Container('authsessionstorage');

is setting a container called authsessionstorage

and this line;

$this->container->userlevel = 0;

is setting a key/value to userlevel / 0

To retrieve this key's value anywhere else you simply need to do something like this;

$container = new Container('authsessionstorage');
echo $container->userlevel;