lithium\storage\Cache::write()

public static method

Writes to the specified cache configuration.

Can handle single- and multi-key writes.

This method has two valid syntaxes depending on if you're storing data using a single key or multiple keys as outlined below.

// To write data to a single-key use the following syntax.
Cache::write('default', 'foo', 'bar', '+1 minute');

// For multi-key writes the $data parameter's role becomes
// the one of the $expiry parameter.
Cache::write('default', array('foo' => 'bar', ... ), '+1 minute');

These two calls are synonymical and demonstrate the two possible ways to specify the expiration time.

Cache::write('default', 'foo', 'bar', '+1 minute');
Cache::write('default', 'foo', 'bar', 60);

Parameters

  • string $name

    Configuration to be used for writing.

  • mixed $key

    Key to uniquely identify the cache entry or an array of key/value pairs for multi-key writes mapping cache keys to the data to be cached.

  • mixed $data

    Data to be cached.

  • string|integer $expiry

    A strtotime() compatible cache time. Alternatively an integer denoting the seconds until the item expires (TTL). If no expiry time is set, then the default cache expiration time set with the cache adapter configuration will be used. To persist an item use Cache::PERSIST.

  • array $options

    Options for the method and strategies.

    • 'strategies' boolean: Indicates if strategies should be used, defaults to true.
    • 'conditions' mixed: A function or item that must return or evaluate to true in order to continue write operation.

Returns

boolean

true on successful cache write, false otherwise. When writing multiple items and an error occurs writing any of the items the whole operation fails and this method will return false.

Filter

This method can be filtered.

Source

	public static function write($name, $key, $data = null, $expiry = null, array $options = array()) {
		$options += array('conditions' => null, 'strategies' => true);

		if (is_callable($options['conditions']) && !$options['conditions']()) {
			return false;
		}
		try {
			$adapter = static::adapter($name);
		} catch (ConfigException $e) {
			return false;
		}
		$key = static::key($key, $data);

		if (is_array($key)) {
			$keys = $key;
			$expiry = $data;
		} else {
			$keys = array($key => $data);
		}

		if ($options['strategies']) {
			foreach ($keys as $key => &$value) {
				$value = static::applyStrategies(__FUNCTION__, $name, $value, array(
					'key' => $key, 'class' => __CLASS__
				));
			}
		}
		$params = compact('keys', 'expiry');

		return static::_filter(__FUNCTION__, $params, function($self, $params) use ($adapter) {
			return $adapter->write($params['keys'], $params['expiry']);
		});
	}