We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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!



11.2k

thanks guys!

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