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

Save array to PHP file with Phalcon Cache

  $arr = array (
    "A" => "juan",
    "B" => "jose",
    "C" => "luis"
  );

Result:

<?php
  $arr = array (
    "A" => "new value",
    "B" => "other new value",
    "C" => "third new value"
  );
?>

for use include()

I create a Backend Cache

<?php

namespace Druphal\Core\Cache\Backend;

use Phalcon\Cache\Backend\File;

class FilePHP extends File
{
    private $fileExtension = '.php';

    /**
     * @inheritDoc
     */
    public function __construct($frontend, array $options)
    {
        if (isset($options['fileExtension'])) {
            $this->fileExtension = $options['fileExtension'];
        }

        parent::__construct($frontend, $options);
    }

    /**
     * @inheritDoc
     */
    public function get($keyName, $lifetime = null)
    {
        $prefixedKey = $this->_prefix . $this->getKey($keyName) . $this->fileExtension;
        $this->_lastKey = $prefixedKey;

        $cacheDir = $this->_options["cacheDir"];

        if (!is_dir($cacheDir)) {
            throw new \Exception("Unexpected inconsistency in options");
        }

        $cacheFile = $cacheDir . $prefixedKey;

        if (file_exists($cacheFile) === true) {
            $frontend = $this->_frontend;

            /**
             * Take the lifetime from the frontend or read it from the set in start()
             */
            if (!$lifetime) {
                $lastLifetime = $this->_lastLifetime;
                if (!$lastLifetime) {
                    $ttl = (int)$frontend->getLifeTime();
                } else {
                    $ttl = (int)$lastLifetime;
                }
            } else {
                $ttl = (int)$lifetime;
            }

            clearstatcache(true, $cacheFile);
            $modifiedTime = (int)filemtime($cacheFile);

            /**
             * Check if the file has expired
             * The content is only retrieved if the content has not expired
             */
            if ($modifiedTime + $ttl > time()) {
                /**
                 * Use file-get-contents to control that the openbase_dir can't be skipped
                 */
                $cachedContent = include $cacheFile;
                if ($cachedContent === false) {
                    throw new \Exception("Cache file " . $cacheFile . " could not be opened");
                }

                if (is_array($cachedContent)) {
                    return $cachedContent;
                } else {
                    /**
                     * Use the frontend to process the content of the cache
                     */
                    $ret = $frontend->afterRetrieve($cachedContent);
                    return $ret;
                }
            }
        }

        return null;
    }

    /**
     * @inheritDoc
     */
    public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true)
    {
        if ($keyName === null) {
            $lastKey = $this->_lastKey;
        } else {
            $lastKey = $this->_prefix . $this->getKey($keyName);
            $this->_lastKey = $lastKey;
        }

        if (!$lastKey) {
            throw new \Exception("Cache must be started first");
        }

        $frontend = $this->_frontend;

        $cacheDir = $this->_options["cacheDir"];

        if (!is_dir($cacheDir)) {
            throw new \Exception("Unexpected inconsistency in options");
        }

        $cacheFile = $cacheDir . $lastKey . $this->fileExtension;

        if ($content === null) {
            $cachedContent = $frontend->getContent();
        } else {
            $cachedContent = $content;
        }

        if (!is_array($cachedContent)) {
            $preparedContent = $frontend->beforeStore($cachedContent);
        } else {
            $preparedContent = $cachedContent;
        }

        /**
         * We use file_put_contents to respect open-base-dir directive
         */
        $status = file_put_contents($cacheFile, '<?php return ' . var_export($preparedContent, true) . ';');

        if ($status === false) {
            throw new \Exception("Cache file " . $cacheFile . " could not be written");
        }

        $isBuffering = $frontend->isBuffering();

        if ($stopBuffer === true) {
            $frontend->stop();
        }

        if ($isBuffering === true) {
            echo $cachedContent;
        }

        $this->_started = false;

        return $status;
    }
}
edited Sep '16

Only for save Array.


    $frontCache = new \Phalcon\Cache\Frontend\None([
        "filetime" => 172800
    ]);

    $cache = new Druphal\Core\Cache\Backend\FilePHP(
        $frontCache,
        [
            "cacheDir" => APP_PATH . "/var/cache/default/config/"
        ]
    );

    $phpFile = $cache->get('my.key');

    if ($phpFile === null) {
        $phpFile = [
            'test' => [1,2,3],
            'other' => ' a string',
            'boolean' => true,
            'Null' => null
        ];
        $cache->save('my.key', $phpFile);
    }

    d($phpFile); // kint() function


40.1k
Accepted
answer

Result:

<?php return array (
  'test' => 
  array (
    0 => 1,
    1 => 2,
    2 => 3,
  ),
  'other' => ' a string',
  'boolean' => true,
  'Null' => NULL,
);