Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Save constant array globally

Hi! how can I save an array (that wont change), so that I can easily get it in my controller/view ??

Controllers are easy, but views cannot access static properties by default.

You'd probably want to set it up as a service, but keep in mind that only objects can be services.

// Globals.php
class Globals {
    protected static $_globals = [];
    public function __construct(array $globals=[]) {
        self::$_globals = array_merge(self::$_globals, $globals);
    }
    public function set($name, $value) {
        self::$_globals[$name] = $value;
    }
    public function get($name) {
        return self::$_globals[$name];
    }
}
// services.php
$di->set('globals', function() {
    return new Globals();
});
// controller
public function someAction() {
    $this->globals->set('someName') = array('foo'=>'bar');
    $foo = $this->globals->get('someName')['foo'];
}
// view
{{ globals.get('someName')['foo'] }}

Don't forget to register the class in the loader!



4.6k

thanks guys!

thx Lajos Bencz, I'll probably just register it as a service or use Phalcon\Registry.