1

I'm new to PHP Phalcon and I'm creating a simple REST API backend, I now encounter a problem.

//define $app in index.php
$app = new Micro($di) ;

In one controller I'm trying to define (add) a global accessible variable between controllers at least.

//However, the followings are all not working.
$this->currentWeixinAccessToken = $access_token ;
$this->getDI()->setShared('currentWeixinAccessToken', $access_token);
$this->$currentWeixinAccessToken = $access_token;
$this->di->setShared('currentWeixinAccessToken', $access_token) ;

They can be defined without error, but when I'm using them in another controller,

$access_token = $this->currentWeixinAccessToken;

The error is,

[Sat Jul 30 22:10:20 2016] PHP Notice:  Access to undefined property currentWeixinAccessToken in /home/tom/src/phalcontest/app/controllers/PostsController.php on line 48

And I found some answers here, but they don't work for me. Cross controller variables in Phalcon

Community
  • 1
  • 1
tomriddle_1234
  • 3,145
  • 6
  • 41
  • 71
  • If controller B extends controller A this should work. But in the way you described it is not possible. I guess you are looking for something like Sessions behavior, but not exactly ;) If that variable is added to the $di you will be able to access it. – Nikolay Mihaylov Jul 31 '16 at 16:20
  • Yes it will like session behavior, but this variable will be all the same through all sessions/ – tomriddle_1234 Aug 02 '16 at 08:42
  • Is the other controller (postcontroller) accessing it from the same request? Or is it on another page – M.Alnashmi Sep 28 '16 at 16:57

1 Answers1

1

When you add something to dependency injector you need to call it through di. That's why you should try using $access_token = $this->di->currentWeixinAccessToken instead in your second controller. Di is by default accessible from controller in full Phalcon, I'm not sure what about micro version. If it doesn't work you can try using \Phalcon\Di::getDefault()->currentWeixinAccessToken or \Phalcon\Di::getDefault()->get('currentWeixinAccessToken')

Luke
  • 2,350
  • 6
  • 26
  • 41
  • @tomriddle_1234 please mark the post as answer if it worked out – Luke Aug 03 '16 at 06:44
  • unfortunately, I tried this and it is not working...Service 'currentWeixinAccessToken' wasn't found in the dependency injection container, Undefined property: Phalcon\Di\FactoryDefault::$currentWeixinAccessToken – tomriddle_1234 Aug 03 '16 at 09:40
  • You're using it wrong. Use one of exact lines I wrote in the answer for instance `\Phalcon\Di::getDefault()->currentWeixinAccessToken` or `\Phalcon\Di::getDefault()->get('currentWeixinAccessToken')` – Luke Aug 03 '16 at 10:00