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;

    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?


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


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:


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;


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')
            ->from( $className )
            ->orderBy( $order . ' ' . $direction );

        $paginator = new Pager( new \Phalcon\Paginator\Adapter\QueryBuilder( array(
            "builder" => $builder,
            "limit"   => 15,
            "page"    => $currentPage
        ) ),
                '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"