類別 yii\caching\MemCache
MemCache 實作了一個基於 memcache 和 memcached 的快取應用程式組件。
MemCache 同時支援 memcache 和 memcached。透過設定 $useMemcached 為 true 或 false,可以讓 MemCache 分別使用 memcached 或 memcache。
MemCache 可以透過設定其 $servers 屬性來配置 memcache 伺服器列表。預設情況下,MemCache 假設有一個 memcache 伺服器在 localhost 的 11211 端口上運行。
請參閱 yii\caching\Cache 以了解 MemCache 支援的常見快取操作。
請注意,memcache 中沒有安全措施來保護資料。系統中任何運行的進程都可以存取 memcache 中的所有資料。
若要使用 MemCache 作為快取應用程式組件,請按如下方式配置應用程式:
[
'components' => [
'cache' => [
'class' => 'yii\caching\MemCache',
'servers' => [
[
'host' => 'server1',
'port' => 11211,
'weight' => 60,
],
[
'host' => 'server2',
'port' => 11211,
'weight' => 40,
],
],
],
],
]
在上述範例中,使用了兩個 memcache 伺服器:server1 和 server2。您可以配置每個伺服器的更多屬性,例如 persistent
、weight
、timeout
。請參閱 yii\caching\MemCacheServer 以取得可用的選項。
有關快取的更多詳細資訊和使用方法,請參閱快取概述指南文章。
公共屬性
屬性 | 類型 | 描述 | 定義於 |
---|---|---|---|
$behaviors | yii\base\Behavior[] | 附加到此組件的行為列表。 | yii\base\Component |
$defaultDuration | integer | 快取條目過期前的預設持續時間(秒)。 | yii\caching\Cache |
$keyPrefix | string | 附加到每個快取鍵的字串前綴,使其在整個快取儲存中全域唯一。 | yii\caching\Cache |
$memcache | \Memcache|\Memcached | 此快取組件使用的 memcache(或 memcached)物件。 | yii\caching\MemCache |
$options | array | Memcached 的選項。 | yii\caching\MemCache |
$password | string | Memcached sasl 密碼。 | yii\caching\MemCache |
$persistentId | string | 用於識別 Memcached 實例的 ID。 | yii\caching\MemCache |
$serializer | array|null|false | 用於序列化和反序列化快取資料的函數。 | yii\caching\Cache |
$servers | yii\caching\MemCacheServer[] | memcache 伺服器配置列表。 | yii\caching\MemCache |
$useMemcached | boolean | 是否使用 memcached 或 memcache 作為底層快取擴展。 | yii\caching\MemCache |
$username | string | Memcached sasl 使用者名稱。 | yii\caching\MemCache |
公共方法
Protected Methods
方法 | 描述 | 定義於 |
---|---|---|
addMemcacheServers() | 將伺服器新增至指定快取的伺服器池。用於 memcache PECL 擴充功能。 | yii\caching\MemCache |
addMemcachedServers() | 將伺服器新增至指定快取的伺服器池。用於 memcached PECL 擴充功能。 | yii\caching\MemCache |
addServers() | 將伺服器新增至指定快取的伺服器池。 | yii\caching\MemCache |
addValue() | 若快取中不包含該鍵值,則將以鍵值識別的值儲存至快取。 | yii\caching\MemCache |
addValues() | 將多個鍵值對新增至快取。 | yii\caching\Cache |
deleteValue() | 從快取中刪除具有指定鍵值的值。這是父類別中宣告的方法的實作。 | yii\caching\MemCache |
flushValues() | 從快取中刪除所有值。 | yii\caching\MemCache |
getValue() | 使用指定的鍵值從快取中檢索值。 | yii\caching\MemCache |
getValues() | 使用指定的鍵值從快取中檢索多個值。 | yii\caching\MemCache |
normalizeDuration() | 標準化持續時間值 | yii\caching\MemCache |
setValue() | 將以鍵值識別的值儲存在快取中。 | yii\caching\MemCache |
setValues() | 在快取中儲存多個鍵值對。 | yii\caching\MemCache |
Property Details
此快取組件使用的 memcache(或 memcached)物件。
Memcached 的選項。此屬性僅在 $useMemcached 為 true 時使用。
另請參閱 https://php.dev.org.tw/manual/en/memcached.setoptions.php。
Memcached sasl 密碼。此屬性僅在 $useMemcached 為 true 時使用。
另請參閱 https://php.dev.org.tw/manual/en/memcached.setsaslauthdata.php。
識別 Memcached 實例的 ID。此屬性僅在 $useMemcached 為 true 時使用。預設情況下,Memcached 實例會在請求結束時銷毀。若要建立在請求之間持續存在的實例,您可以為實例指定唯一的 ID。使用相同 ID 建立的所有實例將共用相同的連線。
另請參閱 https://php.dev.org.tw/manual/en/memcached.construct.php。
memcache 伺服器配置列表。請注意,此屬性的類型在 getter 和 setter 中有所不同。請參閱 getServers() 和 setServers() 以取得詳細資訊。
Memcached sasl 使用者名稱。此屬性僅在 $useMemcached 為 true 時使用。
另請參閱 https://php.dev.org.tw/manual/en/memcached.setsaslauthdata.php。
Method Details
Defined in: yii\base\Component::__call()
呼叫指定的非類別方法。
此方法將檢查是否有任何附加行為具有指定的名稱方法,並在可用時執行它。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在叫用未知方法時隱式呼叫。
public mixed __call ( $name, $params ) | ||
$name | string |
方法名稱 |
$params | array |
方法參數 |
return | mixed |
方法傳回值 |
---|---|---|
throws | yii\base\UnknownMethodException |
當呼叫未知方法時 |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
建構子。
預設實作會執行兩件事
- 使用給定的配置
$config
初始化物件。 - 呼叫 init()。
如果此方法在子類別中被覆寫,建議
- 建構子的最後一個參數是配置陣列,如這裡的
$config
。 - 在建構子的結尾呼叫父類別實作。
public void __construct ( $config = [] ) | ||
$config | array |
將用於初始化物件屬性的名稱-值對 |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
傳回組件屬性的值。
此方法將依以下順序檢查並採取相應措施
- 由 getter 定義的屬性:傳回 getter 結果
- 行為的屬性:傳回行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在執行 $value = $component->property;
時隱式呼叫。
另請參閱 __set()。
public mixed __get ( $name ) | ||
$name | string |
屬性名稱 |
return | mixed |
屬性值或行為的屬性值 |
---|---|---|
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
throws | yii\base\InvalidCallException |
如果屬性為唯寫。 |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
檢查屬性是否已設定,亦即已定義且非空值 (null)。
此方法將依以下順序檢查並採取相應措施
- 由 setter 定義的屬性:傳回屬性是否已設定
- 行為的屬性:傳回屬性是否已設定
- 對於不存在的屬性,傳回
false
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在執行 isset($component->property)
時隱式呼叫。
public boolean __isset ( $name ) | ||
$name | string |
屬性名稱或事件名稱 |
return | boolean |
具名屬性是否已設定 |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
設定組件屬性的值。
此方法將依以下順序檢查並採取相應措施
- 由 setter 定義的屬性:設定屬性值
- 格式為 "on xyz" 的事件:將處理常式附加至事件 "xyz"
- 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
- 行為的屬性:設定行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在執行 $component->property = $value;
時隱式呼叫。
另請參閱 __get()。
public void __set ( $name, $value ) | ||
$name | string |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
---|---|---|
throws | yii\base\InvalidCallException |
如果屬性為唯讀。 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
將組件屬性設定為空值 (null)。
此方法將依以下順序檢查並採取相應措施
- 由 setter 定義的屬性:將屬性值設定為空值 (null)
- 行為的屬性:將屬性值設定為空值 (null)
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在執行 unset($component->property)
時隱式呼叫。
public void __unset ( $name ) | ||
$name | string |
屬性名稱 |
throws | yii\base\InvalidCallException |
如果屬性為唯讀。 |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
public boolean add ( $key, $value, $duration = 0, $dependency = null ) | ||
$key | mixed |
識別要快取的值的鍵值。這可以是簡單的字串或由代表鍵值的因素組成的複雜資料結構。 |
$value | mixed |
要快取的值 |
$duration | integer |
快取值將過期的秒數。0 表示永不過期。 |
$dependency | yii\caching\Dependency|null |
快取項目的相依性。如果相依性變更,則在透過 get() 擷取時,快取中的對應值將失效。如果 $serializer 為 false,則會忽略此參數。 |
return | boolean |
值是否成功儲存到快取中 |
---|
public function add($key, $value, $duration = 0, $dependency = null)
{
if ($dependency !== null && $this->serializer !== false) {
$dependency->evaluateDependency($this);
}
if ($this->serializer === null) {
$value = serialize([$value, $dependency]);
} elseif ($this->serializer !== false) {
$value = call_user_func($this->serializer[0], [$value, $dependency]);
}
$key = $this->buildKey($key);
return $this->addValue($key, $value, $duration);
}
將伺服器新增至指定快取的伺服器池。用於 memcache PECL 擴充功能。
protected void addMemcacheServers ( $cache, $servers ) | ||
$cache | \Memcache | |
$servers | yii\caching\MemCacheServer[] |
protected function addMemcacheServers($cache, $servers)
{
$class = new \ReflectionClass($cache);
$paramCount = $class->getMethod('addServer')->getNumberOfParameters();
foreach ($servers as $server) {
// $timeout is used for memcache versions that do not have $timeoutms parameter
$timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0);
if ($paramCount === 9) {
$cache->addserver(
$server->host,
$server->port,
$server->persistent,
$server->weight,
$timeout,
$server->retryInterval,
$server->status,
$server->failureCallback,
$server->timeout
);
} else {
$cache->addserver(
$server->host,
$server->port,
$server->persistent,
$server->weight,
$timeout,
$server->retryInterval,
$server->status,
$server->failureCallback
);
}
}
}
將伺服器新增至指定快取的伺服器池。用於 memcached PECL 擴充功能。
protected void addMemcachedServers ( $cache, $servers ) | ||
$cache | \Memcached | |
$servers | yii\caching\MemCacheServer[] |
protected function addMemcachedServers($cache, $servers)
{
$existingServers = [];
if ($this->persistentId !== null) {
foreach ($cache->getServerList() as $s) {
$existingServers[$s['host'] . ':' . $s['port']] = true;
}
}
foreach ($servers as $server) {
if (empty($existingServers) || !isset($existingServers[$server->host . ':' . $server->port])) {
$cache->addServer($server->host, $server->port, $server->weight);
}
}
}
將伺服器新增至指定快取的伺服器池。
protected void addServers ( $cache, $servers ) | ||
$cache | \Memcache|\Memcached | |
$servers | yii\caching\MemCacheServer[] | |
throws | yii\base\InvalidConfigException |
---|
protected function addServers($cache, $servers)
{
if (empty($servers)) {
$servers = [new MemCacheServer([
'host' => '127.0.0.1',
'port' => 11211,
])];
} else {
foreach ($servers as $server) {
if ($server->host === null) {
throw new InvalidConfigException("The 'host' property must be specified for every memcache server.");
}
}
}
if ($this->useMemcached) {
$this->addMemcachedServers($cache, $servers);
} else {
$this->addMemcacheServers($cache, $servers);
}
}
protected boolean addValue ( $key, $value, $duration ) | ||
$key | string |
識別要快取的值的鍵值 |
$value | mixed |
要快取的值 |
$duration | integer |
快取值將過期的秒數。0 表示永不過期。 |
return | boolean |
如果值成功儲存到快取中,則為 True,否則為 false |
---|
protected function addValue($key, $value, $duration)
{
$expire = $this->normalizeDuration($duration);
return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
}
Defined in: yii\caching\Cache::addValues()
將多個鍵值對新增至快取。
預設實作多次呼叫 addValue(),以逐一新增值。如果底層快取儲存支援多重新增,則應覆寫此方法以利用該功能。
protected array addValues ( $data, $duration ) | ||
$data | array |
陣列,其中鍵值對應於快取鍵值,而值為儲存的值。 |
$duration | integer |
快取值將過期的秒數。0 表示永不過期。 |
return | array |
失敗的鍵值陣列 |
---|
protected function addValues($data, $duration)
{
$failedKeys = [];
foreach ($data as $key => $value) {
if ($this->addValue($key, $value, $duration) === false) {
$failedKeys[] = $key;
}
}
return $failedKeys;
}
Defined in: yii\base\Component::attachBehavior()
將行為附加至此組件。
此方法將根據給定的配置建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法將行為物件附加至此組件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
行為的名稱。 |
$behavior | string|array|yii\base\Behavior |
行為配置。這可以是下列其中一項
|
return | yii\base\Behavior |
行為物件 |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
定義於: yii\base\Component::attachBehaviors()
將行為列表附加至此組件。
每個行為都以其名稱作為索引,並且應該是一個 yii\base\Behavior 物件、一個指定行為類別的字串,或是一個用於建立行為的配置陣列。
另請參閱 attachBehavior()。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
要附加到元件的行為列表 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
定義於: yii\base\Component::behaviors()
傳回此組件應表現的行為列表。
子類別可以覆寫此方法,以指定它們想要表現為哪些行為。
此方法的傳回值應該是一個行為物件或配置的陣列,以行為名稱作為索引。行為配置可以是指定行為類別的字串,或是一個具有以下結構的陣列
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須繼承自 yii\base\Behavior。行為可以使用名稱或匿名方式附加。當使用名稱作為陣列鍵時,可以使用此名稱稍後透過 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。
在此方法中宣告的行為將會自動(依需求)附加到元件。
public array behaviors ( ) | ||
return | array |
行為配置。 |
---|
public function behaviors()
{
return [];
}
定義於: yii\caching\Cache::buildKey()
從給定的鍵值建立標準化的快取鍵值。
如果給定的鍵是一個僅包含字母數字字元且不超過 32 個字元的字串,則該鍵將會以 $keyPrefix 作為前綴返回。否則,將會透過序列化給定的鍵、應用 MD5 雜湊,並以 $keyPrefix 作為前綴來產生正規化的鍵。
public string buildKey ( $key ) | ||
$key | mixed |
要正規化的鍵 |
return | string |
產生的快取鍵 |
---|
public function buildKey($key)
{
if (is_string($key)) {
$key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
} else {
if ($this->_igbinaryAvailable) {
$serializedKey = igbinary_serialize($key);
} else {
$serializedKey = serialize($key);
}
$key = md5($serializedKey);
}
return $this->keyPrefix . $key;
}
定義於: yii\base\Component::canGetProperty()
傳回指示屬性是否可讀取的值。
如果符合以下條件,則可以讀取屬性:
- 類別具有與指定名稱相關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可讀屬性(當
$checkBehaviors
為 true 時)。
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否可以被讀取 |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
定義於: yii\base\Component::canSetProperty()
傳回指示屬性是否可設定的值。
如果符合以下條件,則可以寫入屬性:
- 類別具有與指定名稱相關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可寫入屬性(當
$checkBehaviors
為 true 時)。
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否可以被寫入 |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
。
定義於: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
定義於: yii\caching\Cache::delete()
從快取中刪除具有指定鍵值的值。
public boolean delete ( $key ) | ||
$key | mixed |
用於識別要從快取中刪除的值的鍵。這可以是簡單的字串或由代表鍵的因素組成的複雜資料結構。 |
return | boolean |
如果在刪除期間沒有發生錯誤 |
---|
public function delete($key)
{
$key = $this->buildKey($key);
return $this->deleteValue($key);
}
從快取中刪除具有指定鍵值的值。這是父類別中宣告的方法的實作。
protected boolean deleteValue ( $key ) | ||
$key | string |
要刪除的值的鍵 |
return | boolean |
如果在刪除期間沒有發生錯誤 |
---|
protected function deleteValue($key)
{
return $this->_cache->delete($key, 0);
}
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
行為的名稱。 |
return | yii\base\Behavior|null |
分離的行為。如果行為不存在,則為 Null。 |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
定義於: yii\base\Component::detachBehaviors()
從組件中分離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
定義於: yii\base\Component::ensureBehaviors()
確保在 behaviors() 中宣告的行為已附加至此組件。
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
定義於: yii\caching\Cache::exists()
檢查快取中是否存在指定的鍵值。
如果資料很大,這可能比從快取中取得值更快。如果快取本身不原生支援此功能,則此方法將嘗試模擬它,但在效能上與取得它沒有改進。請注意,此方法不會檢查與快取資料相關聯的依賴項(如果有的話)是否已更改。因此,呼叫 get() 可能會傳回 false,而 exists 傳回 true。
public boolean exists ( $key ) | ||
$key | mixed |
用於識別快取值的鍵。這可以是簡單的字串或由代表鍵的因素組成的複雜資料結構。 |
return | boolean |
如果快取中存在值則為 True,如果值不在快取中或已過期則為 false。 |
---|
public function exists($key)
{
$key = $this->buildKey($key);
$value = $this->getValue($key);
return $value !== false;
}
public boolean flush ( ) | ||
return | boolean |
清除操作是否成功。 |
---|
public function flush()
{
return $this->flushValues();
}
從快取中刪除所有值。
這是父類別中宣告的方法的實作。
protected boolean flushValues ( ) | ||
return | boolean |
清除操作是否成功。 |
---|
protected function flushValues()
{
return $this->_cache->flush();
}
使用指定的鍵值從快取中檢索值。
public mixed get ( $key ) | ||
$key | mixed |
用於識別快取值的鍵。這可以是簡單的字串或由代表鍵的因素組成的複雜資料結構。 |
return | mixed |
儲存在快取中的值,如果值不在快取中、已過期,或與快取資料相關聯的依賴項已更改,則為 false。 |
---|
public function get($key)
{
$key = $this->buildKey($key);
$value = $this->getValue($key);
if ($value === false || $this->serializer === false) {
return $value;
} elseif ($this->serializer === null) {
$value = unserialize((string)$value);
} else {
$value = call_user_func($this->serializer[1], $value);
}
if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
return $value[0];
}
return false;
}
定義於: yii\base\Component::getBehavior()
傳回具名的行為物件。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
行為名稱 |
return | yii\base\Behavior|null |
行為物件,如果行為不存在,則為 null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
定義於: yii\base\Component::getBehaviors()
傳回附加至此組件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
附加到此元件的行為列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
傳回底層的 memcache (或 memcached) 物件。
public \Memcache|\Memcached getMemcache ( ) | ||
return | \Memcache|\Memcached |
此快取組件使用的 memcache(或 memcached)物件。 |
---|---|---|
throws | yii\base\InvalidConfigException |
如果未載入 memcache 或 memcached 擴充功能 |
public function getMemcache()
{
if ($this->_cache === null) {
$extension = $this->useMemcached ? 'memcached' : 'memcache';
if (!extension_loaded($extension)) {
throw new InvalidConfigException("MemCache requires PHP $extension extension to be loaded.");
}
if ($this->useMemcached) {
$this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached();
if ($this->username !== null || $this->password !== null) {
$this->_cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
$this->_cache->setSaslAuthData($this->username, $this->password);
}
if (!empty($this->options)) {
$this->_cache->setOptions($this->options);
}
} else {
$this->_cache = new \Memcache();
}
}
return $this->_cache;
}
定義於: yii\caching\Cache::getOrSet()
方法結合了 set() 和 get() 方法,以檢索由 $key 識別的值,或者在 $key 沒有可用的快取時,儲存 $callable 執行的結果。
使用範例
public function getTopProducts($count = 10) {
$cache = $this->cache; // Could be Yii::$app->cache
return $cache->getOrSet(['top-n-products', 'n' => $count], function () use ($count) {
return Products::find()->mostPopular()->limit($count)->all();
}, 1000);
}
public mixed getOrSet ( $key, $callable, $duration = null, $dependency = null ) | ||
$key | mixed |
識別要快取的值的鍵值。這可以是簡單的字串或由代表鍵值的因素組成的複雜資料結構。 |
$callable | callable|Closure |
將用於產生要快取的值的可呼叫或閉包。如果您使用的 $callable 可能會傳回 |
$duration | integer|null |
快取過期前的預設持續時間(秒)。如果未設定,將會使用 $defaultDuration 值。 |
$dependency | yii\caching\Dependency|null |
快取項目的依賴項。如果依賴項發生變更,則透過 get() 提取時,快取中的相應值將會失效。如果 $serializer 為 |
return | mixed |
$callable 執行的結果 |
---|
public function getOrSet($key, $callable, $duration = null, $dependency = null)
{
if (($value = $this->get($key)) !== false) {
return $value;
}
$value = call_user_func($callable, $this);
if (!$this->set($key, $value, $duration, $dependency)) {
Yii::warning('Failed to set cache value for key ' . json_encode($key), __METHOD__);
}
return $value;
}
傳回 memcache 或 memcached 伺服器配置。
public yii\caching\MemCacheServer[] getServers ( ) | ||
return | yii\caching\MemCacheServer[] |
memcache 伺服器配置列表。 |
---|
public function getServers()
{
return $this->_servers;
}
使用指定的鍵值從快取中檢索值。
這是父類別中宣告的方法的實作。
protected mixed|false getValue ( $key ) | ||
$key | string |
識別快取值的唯一鍵 |
return | mixed|false |
儲存在快取中的值,如果值不在快取中或已過期,則為 false。 |
---|
protected function getValue($key)
{
return $this->_cache->get($key);
}
使用指定的鍵值從快取中檢索多個值。
protected array getValues ( $keys ) | ||
$keys | array |
識別快取值的鍵列表 |
return | array |
以鍵索引的快取值列表 |
---|
protected function getValues($keys)
{
return $this->useMemcached ? $this->_cache->getMulti($keys) : $this->_cache->get($keys);
}
定義於: yii\base\Component::hasEventHandlers()
傳回指示是否有名稱事件附加任何處理常式的值。
public boolean hasEventHandlers ( $name ) | ||
$name | string |
事件名稱 |
return | boolean |
是否有任何處理常式附加到事件。 |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
定義於: yii\base\Component::hasMethod()
傳回指示是否已定義方法的值。
如果符合以下條件,則定義了方法:
- 類別具有具有指定名稱的方法
- 附加的行為具有給定名稱的方法(當
$checkBehaviors
為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkBehaviors | boolean |
是否將行為的方法視為此元件的方法 |
return | boolean |
是否已定義方法 |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
定義於: yii\base\Component::hasProperty()
傳回指示是否為此組件定義屬性的值。
如果符合以下條件,則定義了屬性:
- 類別具有與指定名稱相關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的屬性(當
$checkBehaviors
為 true 時)。
另請參閱
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否已定義 |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
初始化此應用程式組件。
它會建立 memcache 實例並添加 memcache 伺服器。
public void init ( ) |
public function init()
{
parent::init();
$this->addServers($this->getMemcache(), $this->getServers());
}
public array madd ( $items, $duration = 0, $dependency = null ) | ||
$items | array |
要快取的項目,以鍵值對形式呈現。 |
$duration | integer |
快取值將過期的預設秒數。 0 表示永不過期。 |
$dependency | yii\caching\Dependency|null |
快取項目的依賴性。 如果依賴性發生變化,則在透過 get() 擷取時,快取中對應的值將失效。 如果 $serializer 為 false,則忽略此參數。 |
return | array |
失敗的鍵值陣列 |
---|
public function madd($items, $duration = 0, $dependency = null)
{
return $this->multiAdd($items, $duration, $dependency);
}
定義於: yii\caching\Cache::mget()
使用指定的鍵值從快取中檢索多個值。
某些快取(例如 memcache、apc)允許同時檢索多個快取值,這可能會提高效能。 如果快取本身不支援此功能,則此方法將嘗試模擬它。
public array mget ( $keys ) | ||
$keys | string[] |
識別快取值的字串鍵列表 |
return | array |
與指定鍵相對應的快取值列表。 陣列以(鍵,值)對的形式傳回。 如果值未快取或已過期,則對應的陣列值將為 false。 |
---|
public function mget($keys)
{
return $this->multiGet($keys);
}
public array mset ( $items, $duration = null, $dependency = null ) | ||
$items | array |
要快取的項目,以鍵值對形式呈現。 |
$duration | integer|null |
快取過期前的預設持續時間(秒)。 如果未設定,則使用預設的 $defaultDuration 值。 |
$dependency | yii\caching\Dependency|null |
快取項目的依賴性。 如果依賴性發生變化,則在透過 get() 擷取時,快取中對應的值將失效。 如果 $serializer 為 false,則忽略此參數。 |
return | array |
失敗的鍵值陣列 |
---|
public function mset($items, $duration = null, $dependency = null)
{
return $this->multiSet($items, $duration, $dependency);
}
public array multiAdd ( $items, $duration = 0, $dependency = null ) | ||
$items | array |
要快取的項目,以鍵值對形式呈現。 |
$duration | integer |
快取值將過期的預設秒數。 0 表示永不過期。 |
$dependency | yii\caching\Dependency|null |
快取項目的依賴性。 如果依賴性發生變化,則在透過 get() 擷取時,快取中對應的值將失效。 如果 $serializer 為 false,則忽略此參數。 |
return | array |
失敗的鍵值陣列 |
---|
public function multiAdd($items, $duration = 0, $dependency = null)
{
$data = $this->prepareCacheData($items, $dependency);
return $this->addValues($data, $duration);
}
定義於: yii\caching\Cache::multiGet()
使用指定的鍵值從快取中檢索多個值。
某些快取(例如 memcache、apc)允許同時檢索多個快取值,這可能會提高效能。 如果快取本身不支援此功能,則此方法將嘗試模擬它。
public array multiGet ( $keys ) | ||
$keys | string[] |
識別快取值的字串鍵列表 |
return | array |
與指定鍵相對應的快取值列表。 陣列以(鍵,值)對的形式傳回。 如果值未快取或已過期,則對應的陣列值將為 false。 |
---|
public function multiGet($keys)
{
$keyMap = [];
foreach ($keys as $key) {
$keyMap[$key] = $this->buildKey($key);
}
$values = $this->getValues(array_values($keyMap));
$results = [];
foreach ($keyMap as $key => $newKey) {
$results[$key] = false;
if (isset($values[$newKey])) {
if ($this->serializer === false) {
$results[$key] = $values[$newKey];
} else {
$value = $this->serializer === null ? unserialize($values[$newKey])
: call_user_func($this->serializer[1], $values[$newKey]);
if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
$results[$key] = $value[0];
}
}
}
}
return $results;
}
public array multiSet ( $items, $duration = null, $dependency = null ) | ||
$items | array |
要快取的項目,以鍵值對形式呈現。 |
$duration | integer|null |
快取過期前的預設持續時間(秒)。 如果未設定,則使用預設的 $defaultDuration 值。 |
$dependency | yii\caching\Dependency|null |
快取項目的依賴性。 如果依賴性發生變化,則在透過 get() 擷取時,快取中對應的值將失效。 如果 $serializer 為 false,則忽略此參數。 |
return | array |
失敗的鍵值陣列 |
---|
public function multiSet($items, $duration = null, $dependency = null)
{
if ($duration === null) {
$duration = $this->defaultDuration;
}
$data = $this->prepareCacheData($items, $dependency);
return $this->setValues($data, $duration);
}
標準化持續時間值
另請參閱
protected integer normalizeDuration ( $duration ) | ||
$duration | integer |
protected function normalizeDuration($duration)
{
if ($duration < 0) {
return 0;
}
if ($duration < 2592001) {
return $duration;
}
return $duration + time();
}
定義於: yii\base\Component::off()
從此組件分離現有的事件處理常式。
此方法與 on() 方法相反。
注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理程式,而使用與此萬用字元匹配的純名稱註冊的處理程式將保留。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | string |
事件名稱 |
$handler | callable|null |
要移除的事件處理程式。 如果為 null,則將移除附加到具名事件的所有處理程式。 |
return | boolean |
如果找到並分離處理程式 |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
public boolean offsetExists ( $key ) | ||
$key | string |
識別快取值的鍵 |
#[\ReturnTypeWillChange]
public function offsetExists($key)
{
return $this->get($key) !== false;
}
public mixed offsetGet ( $key ) | ||
$key | string |
識別快取值的鍵 |
return | mixed |
儲存在快取中的值,如果值不在快取中或已過期,則為 false。 |
---|
#[\ReturnTypeWillChange]
public function offsetGet($key)
{
return $this->get($key);
}
定義於: yii\caching\Cache::offsetSet()
將以鍵值識別的值儲存至快取。
如果快取已包含此鍵,則現有的值將被新的值取代。 若要新增到期時間和依賴性,請使用 set() 方法。 此方法是 ArrayAccess 介面所要求的。
public void offsetSet ( $key, $value ) | ||
$key | string |
識別要快取的值的鍵值 |
$value | mixed |
要快取的值 |
#[\ReturnTypeWillChange]
public function offsetSet($key, $value)
{
$this->set($key, $value);
}
定義於: yii\caching\Cache::offsetUnset()
從快取中刪除具有指定鍵值的值。此方法為介面 ArrayAccess 所需。
public void offsetUnset ( $key ) | ||
$key | string |
要刪除的值的鍵 |
#[\ReturnTypeWillChange]
public function offsetUnset($key)
{
$this->delete($key);
}
將事件處理常式附加至事件。
事件處理程式必須是有效的 PHP 回呼。 以下是一些範例
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
事件處理程式必須使用以下簽名定義:
function ($event)
其中 $event
是一個 yii\base\Event 物件,其中包含與事件相關聯的參數。
自 2.0.14 版本起,您可以將事件名稱指定為萬用字元模式
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
另請參閱 off()。
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
事件名稱 |
$handler | 可呼叫 (callable) |
事件處理程式 |
$data | mixed |
事件觸發時要傳遞給事件處理程式的資料。 叫用事件處理程式時,可以透過 yii\base\Event::$data 存取此資料。 |
$append | boolean |
是否將新的事件處理程式附加到現有處理程式列表的末尾。 如果為 false,則新的處理程式將插入到現有處理程式列表的開頭。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
public boolean set ( $key, $value, $duration = null, $dependency = null ) | ||
$key | mixed |
識別要快取的值的鍵值。這可以是簡單的字串或由代表鍵值的因素組成的複雜資料結構。 |
$value | mixed |
要快取的值 |
$duration | integer|null |
快取過期前的預設持續時間(秒)。 如果未設定,則使用預設的 $defaultDuration 值。 |
$dependency | yii\caching\Dependency|null |
快取項目的相依性。如果相依性變更,則在透過 get() 擷取時,快取中的對應值將失效。如果 $serializer 為 false,則會忽略此參數。 |
return | boolean |
值是否成功儲存到快取中 |
---|
public function set($key, $value, $duration = null, $dependency = null)
{
if ($duration === null) {
$duration = $this->defaultDuration;
}
if ($dependency !== null && $this->serializer !== false) {
$dependency->evaluateDependency($this);
}
if ($this->serializer === null) {
$value = serialize([$value, $dependency]);
} elseif ($this->serializer !== false) {
$value = call_user_func($this->serializer[0], [$value, $dependency]);
}
$key = $this->buildKey($key);
return $this->setValue($key, $value, $duration);
}
另請參閱
public void setServers ( $config ) | ||
$config | array |
memcache 或 memcached 伺服器組態列表。 每個元素都必須是一個陣列,其中包含以下鍵:host、port、persistent、weight、timeout、retryInterval、status。 |
public function setServers($config)
{
foreach ($config as $c) {
$this->_servers[] = new MemCacheServer($c);
}
}
protected boolean setValue ( $key, $value, $duration ) | ||
$key | string |
識別要快取的值的鍵值 |
$value | mixed |
要快取的值。 |
$duration | integer |
快取值將過期的秒數。0 表示永不過期。 |
return | boolean |
如果值成功儲存到快取中,則為 True,否則為 false |
---|
protected function setValue($key, $value, $duration)
{
$expire = $this->normalizeDuration($duration);
return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire);
}
在快取中儲存多個鍵值對。
protected array setValues ( $data, $duration ) | ||
$data | array |
陣列,其中鍵對應於快取鍵,而值是要儲存的值 |
$duration | integer |
快取值將過期的秒數。0 表示永不過期。 |
return | array |
失敗的鍵的陣列。 |
---|
protected function setValues($data, $duration)
{
if ($this->useMemcached) {
$expire = $this->normalizeDuration($duration);
// Memcached::setMulti() returns boolean
// @see https://php.dev.org.tw/manual/en/memcached.setmulti.php
return $this->_cache->setMulti($data, $expire) ? [] : array_keys($data);
}
return parent::setValues($data, $duration);
}
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
事件名稱 |
$event | yii\base\Event|null |
事件實例。 如果未設定,將建立預設的 yii\base\Event 物件。 |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
註冊 或 登入 以發表評論。