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

Intercept all queries in db, and use cache in case if cache exists


$di->set('db', function () use ($config, $di) {
    $connection = new DbAdapter($config->database->toArray());

    $eventsManager = $di->getShared('eventsManager');

    $eventsManager->attach('db:beforeQuery', function($event, $connection) {
        return false;
    });

    $connection->setEventsManager($eventsManager);
    return $connection;
});

I have this in my services, this code "catch" all queries, this is fine. But my goal is use global cache handler which will catch all queries and use them as keys in the cache system. Could someone make a suggestion regarding this?

Thanks

edited Jun '16

Then just connect your cache service there, check simply like:

    //1st try to fetch table definition from lib mem daemon
            $modelCache = static::$modelsMetadata->read($source);

            //If we already have result set in lib memory daemon, return data straight away
            if ($modelCache) return $modelCache; //return model's metadata map
            else; //query DB since we don't have cached content


12.2k

Thanks for your reply.

This is standart solution, my question is manly about where can I set such kind of interception. Because for example for models I can set event "afterFetch". For example:


<?php

namespace PM;

use \Phalcon\Events\Manager as EventsManager;

class BaseModel extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $eventsManager = new EventsManager();

        $eventsManager->attach('model', function($event, $model) {
            return true;
        });

        $this->setEventsManager($eventsManager);
    }
}

but this is not fits for me.

I know about possibility override the methods Model::find() and Model::findOne(). But this is not fit for me either because I can use Builder or Paginator like this


$builder     = Di::getDefault()->get('modelsManager')
            ->createBuilder()
            ->from( $className )
            ->orderBy( $order . ' ' . $direction );

        $paginator = new Pager( new \Phalcon\Paginator\Adapter\QueryBuilder( array(
            "builder" => $builder,
            "limit"   => 15,
            "page"    => $currentPage
        ) ),
            array(
                'rangeLength' => 7
            )
        );

According to all of said above I'm searching a propper solution shich will allow to me get all queries roughly said "beforeExecuteSelect"