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

[SOLVED] Access DI from static method in model

I wrote the following code in index.php

    $di->set('cache', function(){
        $front = new Phalcon\Cache\Frontend\Data([]);
        $cache = new Phalcon\Cache\Backend\Apc($front, []);
        return $cache;
    });

How I can use cache to get/save data from static methods in Models?

            $di = \Phalcon\DI::getDefault();

            if ($di->cache->exists("cache-key")) {
                return $di->cache->get("cache-key");
            } else {

Looks like I can not get the proper value using the code above. Thanks.



98.9k
Accepted
answer

Try:

$di->set('cache', function(){
    $front = new Phalcon\Cache\Frontend\Data([]);
    $cache = new Phalcon\Cache\Backend\Apc($front, []);
    return $cache;
}, true);

And:

$di = \Phalcon\DI::getDefault();

$cache = $di['cache'];
if ($cache->exists("cache-key")) {
    return $cache->get("cache-key");
} else {