4

I added a lib called MyLib, inside my App/Lib folder in CakePHP 2.5.5:

App::uses('CakeSession', 'Model/Datasource');

class MyLib {

    public static function myfunction1() {
        return CakeSession::read('Config.language');
    }

    public static function myfunction2() {
        return $_SESSION;
    }

}

I defined it inside App/Config/bootstrap.php:

App::uses('MyLib', 'Lib');

Inside MyController1 I use it like this.
myAction gives empty output: When I check I see that session data is empty for MyController1.

class MyController1 {

   function myAction1(){

    echo MyLib::myfunction1();
    print_r(MyLib::myfunction2());

   }
}

I also have another controller named MyController2.
When I use MyLib::myfunction1() everything works fine for MyController2.

class MyController2 {

   function myAction2(){

    echo MyLib::myfunction1();
    print_r(MyLib::myfunction2());

  }
}

What would make session to be empty for some controller / action ?

trante
  • 33,518
  • 47
  • 192
  • 272
  • 1
    Where do you write 'Config.language' to session? – bancer Nov 07 '14 at 22:33
  • As the result is different between two controllers, could it be the classical problem of a `beforeFilter()` not calling its parent `beforeFilter()` defined in AppController that would do some required stuff in order for your lib to work ? – nIcO Nov 12 '14 at 15:45

3 Answers3

1

You have a typo when loading your library.

App::uses('MyLib ', 'Lib');

See the blank space after MyLib? It should be:

App::uses('MyLib', 'Lib');

You are also misusing print_r function. The second parameter tells the function if you want to return the information rather than print it. You should do:

print_r(MyLib::myfunction2());

Although you also can do this:

$my_session = print_r(MyLib::myfunction2(),true);
echo $my_session;

http://php.net/manual/en/function.print-r.php

Deimoks
  • 728
  • 6
  • 20
1

I had a similar problem. This is an ugly solution but it helped in my case. Try to add App::uses in method. Something like this:

class MyController2 {

   function myAction2(){
    App::uses('MyLib', 'Lib');
    echo MyLib::myfunction1();
    print_r(MyLib::myfunction2());
   }
}
Marko Vasic
  • 690
  • 9
  • 27
1

I'm pretty sure you have a problem elsewhere in your code that you are not showing us (I guess you have shown some example code here that isn't your real code).

I have tested with your exact code and both controllers show exactly the same. There's absolutely no reason why one controller would show something different unless that controller contains something else that the other one doesn't have.

BadHorsie
  • 14,135
  • 30
  • 117
  • 191