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

Overwrite Phalcon\Cache method beforeStore()

Hey guys,

i'm using \Phalcon\Cache\Frontend\Json but i wanted to set additional options for the json_encode function in here: https://api.phalcon.io/source/Phalcon/Cache/Frontend/Json.html

I've tried to overwrite beforeStore in my services file but without success.

    $di->set('cache', function() use ($config) {
        $frontend = new \Phalcon\Cache\Frontend\Json(array('lifetime' => 172800));
        $frontend->beforeStore = function($data) {
            die('Yay we are here');
        };
        ....

Any suggestions?



993

You should create a new class extends Phalcon\Cache\Frontend\Json to do this.

PHP can not overwrite object method in runtime like javascript.



79.0k
Accepted
answer
edited Dec '15

Pretty much, the only way of doing this is 'manual' override of the native class/method.

Just create a new class inside your Service container which extends \Phalcon\Cache\Frontend\Json.

So your construct would look like this:

        $frontend = new MyOverrideClass(array('lifetime' => 172800));

And then define method you wish for inside class MyOverrideClass:

    public function beforeStore(array $dat)
    {
        $dat['addon'] = mt_rand(); //Add another key/value
        return json_encode($dat);
    }