Phalcon\Cache\Backend\Database::save PHP Метод

save() публичный Метод

public save ( string $keyName = null, string $content = null, integer $lifetime = null, boolean $stopBuffer = true ) : boolean
$keyName string
$content string
$lifetime integer
$stopBuffer boolean
Результат boolean
    public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true)
    {
        if ($keyName === null) {
            $prefixedKey = $this->_lastKey;
        } else {
            $prefixedKey = $this->getPrefixedIdentifier($keyName);
        }
        if (!$prefixedKey) {
            throw new Exception('The cache must be started first');
        }
        /** @var \Phalcon\Cache\FrontendInterface $frontend */
        $frontend = $this->getFrontend();
        if ($content === null) {
            $cachedContent = $frontend->getContent();
        } else {
            $cachedContent = $content;
        }
        if (null === $lifetime) {
            $lifetime = $frontend->getLifetime();
        }
        $lifetime = time() + $lifetime;
        // Check if the cache already exist
        $sql = "SELECT data, lifetime FROM {$this->table} WHERE key_name = ?";
        $cache = $this->db->fetchOne($sql, Db::FETCH_ASSOC, [$prefixedKey]);
        if (!$cache) {
            $status = $this->db->execute("INSERT INTO {$this->table} VALUES (?, ?, ?)", [$prefixedKey, $frontend->beforeStore($cachedContent), $lifetime]);
        } else {
            $status = $this->db->execute("UPDATE {$this->table} SET data = ?, lifetime = ? WHERE key_name = ?", [$frontend->beforeStore($cachedContent), $lifetime, $prefixedKey]);
        }
        if (!$status) {
            throw new Exception('Failed storing data in database');
        }
        if ($stopBuffer) {
            $frontend->stop();
        }
        if ($frontend->isBuffering()) {
            echo $content;
        }
        $this->_started = false;
        return $status;
    }

Usage Example

Пример #1
0
 protected function runTests(CacheBackend $backend, $lifetime = null)
 {
     $backend->save($this->key, $this->data, $lifetime);
     $this->assertTrue($backend->exists($this->key));
     $this->assertEquals($this->data, $backend->get($this->key));
     $this->assertNotEmpty($backend->queryKeys());
     $this->assertNotEmpty($backend->queryKeys('DB_'));
     $this->assertTrue($backend->delete($this->key));
     $this->assertFalse($backend->delete($this->key));
     if (null !== $lifetime) {
         $backend->save($this->key, $this->data, $lifetime);
         $this->assertTrue($backend->exists($this->key, $lifetime));
         $this->assertEquals($this->data, $backend->get($this->key, $lifetime));
         $backend->save($this->key, $this->data, -$lifetime);
         $this->assertFalse($backend->exists($this->key, -$lifetime));
     }
 }