Setting up a cache service


Nov '14

Dec '14

2

1559

1


Thien
31.3k
edited Nov '14
Nov '14

In Phalcon, the cache consists of two parts, a frontend cache that handles cache expiration and transformation, and the backend cache that handles the reads and writes when requested to by the frontend. Here is an example of a cache service. We could simply add this to our service.php file.

    <?php

    //Set the models cache service
    $di->set('modelsCache', function() {

        //Cache data for one day by default
        $frontCache = new \Phalcon\Cache\Frontend\Data(array(
            "lifetime" => 86400
        ));

        //Memcached connection settings
        $cache = new Phalcon\Cache\Backend\Apc ($frontendcache, array(
            'prefix' => 'cache'
        ));

        return $cache;
    });

Then in your models pass a 'cache' parameter to tell the ORM the resultset must be cached:

    <?php
    // Get products without caching
    $products = Products::find();

    // Just cache the resultset. The cache will expire in 1 hour (3600 seconds)
    $products = Products::find(array(
        "cache" => array("key" => "my-cache")
    ));

    // Cache the resultset for only for 5 minutes
    $products = Products::find(array(
        "cache" => array("key" => "my-cache", "lifetime" => 300)
    ));

    // Using a custom cache
    $products = Products::find(array("cache" => $myCache));

Rajesh
101
edited Dec '14
Dec '14

What about in "Phalcon\Mvc\Model\Query\Builder" & also in "\Phalcon\Paginator\Adapter\QueryBuilder"


kenjis
163
    // Just cache the resultset. The cache will expire in 1 hour (3600 seconds)
    $products = Products::find(array(
        "cache" => array("key" => "my-cache")
    ));

Why will the cache expire in 1 hour (3600 seconds)? Where does 3600 come from?


Thien
31.3k

@Ralesh Phalcon\Mvc\Model\Query\Builder it will usually get data of Model not paginator in while \Phalcon\Paginator\Adapter\QueryBuilder get data as well as paginator you can refer here http://docs.phalconphp.com/en/latest/api/Phalcon_Paginator_Adapter_QueryBuilder.html