4

Failed to get a session component inside AppController

 2 years ago
source link: https://www.codesd.com/item/failed-to-get-a-session-component-inside-appcontroller.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Failed to get a session component inside AppController

advertisements

I need to get the roles of a user from the database.
I want to do it once and before everything. So I call a function from AppController constructor, which uses the session component. The function is given below

public function getRoles() {
    if ($this->Session->check('user_name')) {
        $username = $this->Session->read('user_name');
        $userdesc = $this->Session->read('user_desc');
        if ($userdesc === 'Student') {
            $this->roles['Student'] = true;
        } elseif ($userdesc === 'Faculty') {
            $this->roles['Teacher'] = true;

            $this->loadModel('UserRole');
            $userRolesList = $this->UserRole->getUserRolesList($username);

            $this->loadModel('Role');
            $rolesList = $this->Role->getRolesList();

            foreach($userRolesList as $userRole)
            {
                $this->roles[$rolesList[$userRole['UserRole']['role_id']]] = true;
            }
        }
    }
}

I load session component using an array. But I can't use $this->Session. If I load the component on the fly the function gives other errors. But if I call this function from beforeFilter() it creates no problem. Why I can't do it inside the constructor?


you cant use $this inside constructor as $this is not instanciated yet. explained here PHP: using $this in constructor


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK