1

In cakephp 2.x I could define a variable in app model public $someVar = false; and it would be accessible in all models. I could even access/set it from controller for any model: e.g.

$this->User->someVar = true;

Since there is no app model, is there any way to achieve the same thing in cake 3. I have global event listeners set up as in this answer

Cakephp 3 callbacks, behaviors for all models

So, the purpose is to have a variable, which will be accessible in those global listeners, all models' callbacks as well as from controller through model's object - similar to cake 2: for app model's callbacks, all models' callbacks and from controller respectively.

edit: would not prefer to use Configure

Thanks

Community
  • 1
  • 1
dav
  • 8,931
  • 15
  • 76
  • 140

1 Answers1

2

It looks like I figured it out

Create a Behavior and load it in initialize global event. similar to example here Cakephp 3 callbacks, behaviors for all models

This way it will be available in all models and callbacks. Create a variable in that behavior public $someVar = null. However accessing directly the behavior's variable is not possible (as it is treated as an association) https://github.com/cakephp/cakephp/issues/9153

So, you can define method to set/get the value

// inside Behavior
public function setSomeVar($val = null) {
    if ($val === null) {
        return $val;
    }

    return $this->myVar = $val;
}

To access/modify that variable

// inside callbacks/event listeners
$event->subject()->setSomeVar();       // to get
$event->subject()->setSomeVar('smth'); // to set

// from controller
$this->Users->setSomeVar();          // to get
$this->Users->setSomeVar('smth');    // to set
Community
  • 1
  • 1
dav
  • 8,931
  • 15
  • 76
  • 140