本文整理汇总了PHP中Gdn::cache方法的典型用法代码示例。如果您正苦于以下问题:PHP Gdn::cache方法的具体用法?PHP Gdn::cache怎么用?PHP Gdn::cache使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Gdn
的用法示例。
在下文中一共展示了Gdn::cache方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
/**
* Initialize a new instance of the {@link CategoryCollection} class.
*
* @param Gdn_SQLDriver|null $sql The database layer dependency.
* @param Gdn_Cache|null $cache The cache layer dependency.
*/
public function __construct(Gdn_SQLDriver $sql = null, Gdn_Cache $cache = null)
{
if ($sql === null) {
$sql = Gdn::sql();
}
$this->sql = $sql;
if ($cache === null) {
$cache = Gdn::cache();
}
$this->cache = $cache;
}
示例2: getCount
protected function getCount($Table)
{
// Try and get the count from the cache.
$Key = "{$Table}.CountRows";
$Count = Gdn::cache()->get($Key);
if ($Count !== Gdn_Cache::CACHEOP_FAILURE) {
return $Count;
}
// The count wasn't in the cache so grab it from the table.
$Count = Gdn::sql()->select($Table . 'ID', 'count', 'CountRows')->from($Table)->get()->value('CountRows');
// Save the value to the cache.
Gdn::cache()->store($Key, $Count, array(Gdn_Cache::FEATURE_EXPIRY => 5 * 60 + mt_rand(0, 30)));
return $Count;
}
示例3: __construct
/**
* Initialize a new instance of the {@link CategoryCollection} class.
*
* @param Gdn_SQLDriver|null $sql The database layer dependency.
* @param Gdn_Cache|null $cache The cache layer dependency.
*/
public function __construct(Gdn_SQLDriver $sql = null, Gdn_Cache $cache = null)
{
if ($sql === null) {
$sql = Gdn::sql();
}
$this->sql = $sql;
if ($cache === null) {
$cache = Gdn::cache();
}
$this->cache = $cache;
$this->setStaticCalculator([$this, 'defaultCalculator']);
$this->setUserCalculator(function (&$category) {
// do nothing
});
}
示例4: save
/**
* Save a message.
*
* @param array $FormPostValues Message data.
* @param bool $Settings
* @return int The MessageID.
*/
public function save($FormPostValues, $Settings = false)
{
// The "location" is packed into a single input with a / delimiter. Need to explode it into three different fields for saving
$Location = val('Location', $FormPostValues, '');
if ($Location != '') {
$Location = explode('/', $Location);
$Application = val(0, $Location, '');
if (in_array($Application, $this->_SpecialLocations)) {
$FormPostValues['Application'] = null;
$FormPostValues['Controller'] = $Application;
$FormPostValues['Method'] = null;
} else {
$FormPostValues['Application'] = $Application;
$FormPostValues['Controller'] = val(1, $Location, '');
$FormPostValues['Method'] = val(2, $Location, '');
}
}
Gdn::cache()->remove('Messages');
return parent::save($FormPostValues, $Settings);
}
示例5: addView
/**
* Increments view count for the specified discussion.
*
* @since 2.0.0
* @access public
*
* @param int $DiscussionID Unique ID of discussion to get +1 view.
*/
public function addView($DiscussionID)
{
$IncrementBy = 0;
if (c('Vanilla.Views.Denormalize', false) && Gdn::cache()->activeEnabled() && Gdn::cache()->Type() != Gdn_Cache::CACHE_TYPE_NULL) {
$WritebackLimit = c('Vanilla.Views.DenormalizeWriteback', 10);
$CacheKey = sprintf(DiscussionModel::CACHE_DISCUSSIONVIEWS, $DiscussionID);
// Increment. If not success, create key.
$Views = Gdn::cache()->increment($CacheKey);
if ($Views === Gdn_Cache::CACHEOP_FAILURE) {
Gdn::cache()->store($CacheKey, 1);
}
// Every X views, writeback to Discussions
if ($Views % $WritebackLimit == 0) {
$IncrementBy = floor($Views / $WritebackLimit) * $WritebackLimit;
Gdn::cache()->Decrement($CacheKey, $IncrementBy);
}
} else {
$IncrementBy = 1;
}
if ($IncrementBy) {
$this->SQL->update('Discussion')->set('CountViews', "CountViews + {$IncrementBy}", false)->where('DiscussionID', $DiscussionID)->put();
}
}
示例6: saveCache
/**
* Save the provided library's data to the on disk location.
*
* @param string $CacheName name of cache library
* @return void
*/
public static function saveCache($CacheName)
{
if ($CacheName != 'locale') {
return;
}
if (!array_key_exists($CacheName, self::$Caches)) {
return false;
}
$UseCache = Gdn::cache()->type() == Gdn_Cache::CACHE_TYPE_MEMORY && Gdn::cache()->activeEnabled();
if ($UseCache) {
$CacheKey = sprintf(Gdn_LibraryMap::CACHE_CACHE_NAME_FORMAT, $CacheName);
$Stored = Gdn::cache()->store($CacheKey, self::$Caches[$CacheName]['cache']);
} else {
$FileName = self::$Caches[$CacheName]['ondisk'];
$CacheContents = "";
foreach (self::$Caches[$CacheName]['cache'] as $SectionTitle => $SectionData) {
$CacheContents .= "[{$SectionTitle}]\n";
foreach ($SectionData as $StoreKey => $StoreValue) {
$CacheContents .= "{$StoreKey} = \"{$StoreValue}\"\n";
}
}
try {
// Fix slashes to get around parse_ini_file issue that drops off \ when loading network file.
$CacheContents = str_replace("\\", "/", $CacheContents);
Gdn_FileSystem::saveFile(PATH_CACHE . DS . $FileName, $CacheContents, LOCK_EX);
} catch (Exception $e) {
}
}
}
示例7: save
/**
*
*
* @return bool|null
* @throws Exception
*/
public function save()
{
if (!$this->Dirty) {
return null;
}
$this->EventArguments['ConfigDirty'] =& $this->Dirty;
$this->EventArguments['ConfigNoSave'] = false;
$this->EventArguments['ConfigType'] = $this->Type;
$this->EventArguments['ConfigSource'] = $this->Source;
$this->EventArguments['ConfigData'] = $this->Settings;
$this->fireEvent('BeforeSave');
if ($this->EventArguments['ConfigNoSave']) {
$this->Dirty = false;
return true;
}
// Check for and fire callback if one exists
if ($this->Callback && is_callable($this->Callback)) {
$CallbackOptions = array();
if (!is_array($this->CallbackOptions)) {
$this->CallbackOptions = array();
}
$CallbackOptions = array_merge($CallbackOptions, $this->CallbackOptions, array('ConfigDirty' => $this->Dirty, 'ConfigType' => $this->Type, 'ConfigSource' => $this->Source, 'ConfigData' => $this->Settings, 'SourceObject' => $this));
$ConfigSaved = call_user_func($this->Callback, $CallbackOptions);
if ($ConfigSaved) {
$this->Dirty = false;
return true;
}
}
switch ($this->Type) {
case 'file':
if (empty($this->Source)) {
trigger_error(errorMessage('You must specify a file path to be saved.', 'Configuration', 'Save'), E_USER_ERROR);
}
$CheckWrite = $this->Source;
if (!file_exists($CheckWrite)) {
$CheckWrite = dirname($CheckWrite);
}
if (!is_writable($CheckWrite)) {
throw new Exception(sprintf(t("Unable to write to config file '%s' when saving."), $this->Source));
}
$Group = $this->Group;
$Data =& $this->Settings;
ksort($Data);
// Check for the case when the configuration is the group.
if (is_array($Data) && count($Data) == 1 && array_key_exists($Group, $Data)) {
$Data = $Data[$Group];
}
// Do a sanity check on the config save.
if ($this->Source == Gdn::config()->defaultPath()) {
// Log root config changes
try {
$LogData = $this->Initial;
$LogData['_New'] = $this->Settings;
LogModel::insert('Edit', 'Configuration', $LogData);
} catch (Exception $Ex) {
}
if (!isset($Data['Database'])) {
if ($Pm = Gdn::pluginManager()) {
$Pm->EventArguments['Data'] = $Data;
$Pm->EventArguments['Backtrace'] = debug_backtrace();
$Pm->fireEvent('ConfigError');
}
return false;
}
}
// Write config data to string format, ready for saving
$FileContents = Gdn_Configuration::format($Data, array('VariableName' => $Group, 'WrapPHP' => true, 'ByLine' => true));
if ($FileContents === false) {
trigger_error(errorMessage('Failed to define configuration file contents.', 'Configuration', 'Save'), E_USER_ERROR);
}
// Save to cache if we're into that sort of thing
$FileKey = sprintf(Gdn_Configuration::CONFIG_FILE_CACHE_KEY, $this->Source);
if ($this->Configuration && $this->Configuration->caching() && Gdn::cache()->type() == Gdn_Cache::CACHE_TYPE_MEMORY && Gdn::cache()->activeEnabled()) {
$CachedConfigData = Gdn::cache()->store($FileKey, $Data, array(Gdn_Cache::FEATURE_NOPREFIX => true, Gdn_Cache::FEATURE_EXPIRY => 3600));
}
$TmpFile = tempnam(PATH_CONF, 'config');
$Result = false;
if (file_put_contents($TmpFile, $FileContents) !== false) {
chmod($TmpFile, 0775);
$Result = rename($TmpFile, $this->Source);
}
if ($Result) {
if (function_exists('apc_delete_file')) {
// This fixes a bug with some configurations of apc.
@apc_delete_file($this->Source);
} elseif (function_exists('opcache_invalidate')) {
@opcache_invalidate($this->Source);
}
}
$this->Dirty = false;
return $Result;
break;
case 'json':
case 'array':
//.........这里部分代码省略.........
示例8: getCommentCounts
/**
* Takes a set of discussion identifiers and returns their comment counts in the same order.
*/
public function getCommentCounts()
{
$this->AllowJSONP(true);
$vanilla_identifier = val('vanilla_identifier', $_GET);
if (!is_array($vanilla_identifier)) {
$vanilla_identifier = array($vanilla_identifier);
}
$vanilla_identifier = array_unique($vanilla_identifier);
$FinalData = array_fill_keys($vanilla_identifier, 0);
$Misses = array();
$CacheKey = 'embed.comments.count.%s';
$OriginalIDs = array();
foreach ($vanilla_identifier as $ForeignID) {
$HashedForeignID = ForeignIDHash($ForeignID);
// Keep record of non-hashed identifiers for the reply
$OriginalIDs[$HashedForeignID] = $ForeignID;
$RealCacheKey = sprintf($CacheKey, $HashedForeignID);
$Comments = Gdn::cache()->get($RealCacheKey);
if ($Comments !== Gdn_Cache::CACHEOP_FAILURE) {
$FinalData[$ForeignID] = $Comments;
} else {
$Misses[] = $HashedForeignID;
}
}
if (sizeof($Misses)) {
$CountData = Gdn::sql()->select('ForeignID, CountComments')->from('Discussion')->where('Type', 'page')->whereIn('ForeignID', $Misses)->get()->resultArray();
foreach ($CountData as $Row) {
// Get original identifier to send back
$ForeignID = $OriginalIDs[$Row['ForeignID']];
$FinalData[$ForeignID] = $Row['CountComments'];
// Cache using the hashed identifier
$RealCacheKey = sprintf($CacheKey, $Row['ForeignID']);
Gdn::cache()->store($RealCacheKey, $Row['CountComments'], array(Gdn_Cache::FEATURE_EXPIRY => 60));
}
}
$this->setData('CountData', $FinalData);
$this->DeliveryMethod = DELIVERY_METHOD_JSON;
$this->DeliveryType = DELIVERY_TYPE_DATA;
$this->render();
}
示例9: logAccess
/**
* Log the access of a resource.
*
* Since resources can be accessed with every page view this event will only log when the cache is enabled
* and once every five minutes.
*
* @param string $event The name of the event to log.
* @param string $level The log level of the event.
* @param string $message The log message format.
* @param array $context Additional information to pass to the event.
*/
public static function logAccess($event, $level, $message, $context = array())
{
// Throttle the log access to 1 event every 5 minutes.
if (Gdn::cache()->activeEnabled()) {
$userID = Gdn::session()->UserID;
$path = Gdn::request()->path();
$key = "log:{$event}:{$userID}:{$path}";
if (Gdn::cache()->get($key) === false) {
self::event($event, $level, $message, $context);
Gdn::cache()->store($key, time(), array(Gdn_Cache::FEATURE_EXPIRY => 300));
}
}
}
示例10: ping
/**
*
*
* @throws Exception
*/
public function ping()
{
$start = microtime(true);
$this->setData('pong', true);
$this->MasterView = 'empty';
$this->CssClass = 'Home';
$valid = true;
// Test the cache.
if (Gdn::cache()->activeEnabled()) {
$k = betterRandomString(20);
Gdn::cache()->store($k, 1);
Gdn::cache()->increment($k, 1);
$v = Gdn::cache()->get($k);
if ($v !== 2) {
$valid = false;
$this->setData('cache', false);
} else {
$this->setData('cache', true);
}
} else {
$this->setData('cache', 'disabled');
}
// Test the db.
try {
$users = Gdn::sql()->get('User', 'UserID', 'asc', 1);
$this->setData('database', true);
} catch (Exception $ex) {
$this->setData('database', false);
$valid = false;
}
$this->EventArguments['Valid'] =& $valid;
$this->fireEvent('Ping');
if (!$valid) {
$this->statusCode(500);
}
$time = microtime(true) - $start;
$this->setData('time', Gdn_Format::timespan($time));
$this->setData('time_s', $time);
$this->setData('valid', $valid);
$this->title('Ping');
$this->render();
}
示例11: setUserMeta
/**
* Sets UserMeta data to the UserMeta table.
*
* This method takes a UserID, Key, and Value, and attempts to set $Key = $Value for $UserID.
* $Key can be an SQL wildcard, thereby allowing multiple variations of a $Key to be set. $UserID
* can be an array, thereby allowing multiple users' $Keys to be set to the same $Value.
*
* ++ Before any queries are run, $Key is converted to its fully qualified format (Plugin.<PluginName> prepended)
* ++ to prevent collisions in the meta table when multiple plugins have similar key names.
*
* If $Value == null, the matching row(s) are deleted instead of updated.
*
* @param $UserID int UserID or array of UserIDs
* @param $Key string relative user key
* @param $Value mixed optional value to set, null to delete
* @return void
*/
public function setUserMeta($UserID, $Key, $Value = null)
{
if (Gdn::cache()->activeEnabled()) {
if (is_array($UserID)) {
foreach ($UserID as $ID) {
$this->SetUserMeta($ID, $Key, $Value);
}
return;
}
$UserMeta = $this->GetUserMeta($UserID);
if (!stristr($Key, '%')) {
if ($Value === null) {
unset($UserMeta[$Key]);
} else {
$UserMeta[$Key] = $Value;
}
} else {
$MatchKey = str_replace('%', '*', $Key);
foreach ($UserMeta as $UserMetaKey => $UserMetaValue) {
if (fnmatch($MatchKey, $UserMetaKey)) {
if ($Value === null) {
unset($UserMeta[$UserMetaKey]);
} else {
$UserMeta[$UserMetaKey] = $Value;
}
}
}
}
$CacheKey = 'UserMeta_' . $UserID;
Gdn::cache()->store($CacheKey, $UserMeta, array(Gdn_Cache::FEATURE_EXPIRY => 3600));
// Update the DB.
$this->SQL->reset();
if ($Value === null) {
$Q = $this->SQL->where('UserID', $UserID);
if (stristr($Key, '%')) {
$Q->like('Name', $Key);
} else {
$Q->where('Name', $Key);
}
$Q->delete('UserMeta');
} else {
$Px = $this->SQL->Database->DatabasePrefix;
$Sql = "insert {$Px}UserMeta (UserID, Name, Value) values(:UserID, :Name, :Value) on duplicate key update Value = :Value1";
$Params = array(':UserID' => $UserID, ':Name' => $Key, ':Value' => $Value, ':Value1' => $Value);
$this->Database->query($Sql, $Params);
}
return;
}
if (is_null($Value)) {
// Delete
$UserMetaQuery = Gdn::sql();
if (is_array($UserID)) {
$UserMetaQuery->whereIn('UserID', $UserID);
} else {
$UserMetaQuery->where('UserID', $UserID);
}
if (stristr($Key, '%')) {
$UserMetaQuery->like('Name', $Key);
} else {
$UserMetaQuery->where('Name', $Key);
}
$UserMetaQuery->delete('UserMeta');
} else {
// Set
if (!is_array($UserID)) {
$UserID = array($UserID);
}
foreach ($UserID as $UID) {
try {
Gdn::sql()->insert('UserMeta', array('UserID' => $UID, 'Name' => $Key, 'Value' => $Value));
} catch (Exception $e) {
Gdn::sql()->update('UserMeta', array('Value' => $Value), array('UserID' => $UID, 'Name' => $Key))->put();
}
}
}
return;
}
示例12: getPermissionsByRole
/**
* Get the permissions for one or more roles.
*
* @param int $roleID The role to get the permissions for.
* @return array Returns a permission array suitable for use in a session.
*/
public function getPermissionsByRole($roleID)
{
$inc = Gdn::userModel()->getPermissionsIncrement();
$key = "perms:{$inc}:role:{$roleID}";
$permissions = Gdn::cache()->get($key);
if ($permissions === Gdn_Cache::CACHEOP_FAILURE) {
$sql = clone $this->SQL;
$sql->reset();
// Select all of the permission columns.
$permissionColumns = $this->permissionColumns();
foreach ($permissionColumns as $columnName => $value) {
$sql->select('p.`' . $columnName . '`', 'MAX');
}
$sql->from('Permission p')->where('p.RoleID', $roleID)->select(array('p.JunctionTable', 'p.JunctionColumn', 'p.JunctionID'))->groupBy(array('p.JunctionTable', 'p.JunctionColumn', 'p.JunctionID'));
$permissions = $sql->get()->resultArray();
$permissions = UserModel::compilePermissions($permissions);
Gdn::cache()->store($key, $permissions);
}
return $permissions;
}
示例13: selectByScore
/**
* Select content based on its Score.
*
* @param array|int $Parameters
* @return array|false
*/
protected function selectByScore($Parameters)
{
if (!is_array($Parameters)) {
$MinScore = $Parameters;
} else {
$MinScore = val('Score', $Parameters, null);
}
if (!is_integer($MinScore)) {
$MinScore = false;
}
// Check cache
$SelectorScoreCacheKey = "modules.promotedcontent.score.{$MinScore}";
$Content = Gdn::cache()->get($SelectorScoreCacheKey);
if ($Content == Gdn_Cache::CACHEOP_FAILURE) {
// Get matching Discussions
$Discussions = array();
if ($this->ShowDiscussions()) {
$Discussions = Gdn::sql()->select('d.*')->from('Discussion d')->orderBy('DateInserted', 'DESC')->limit($this->Limit);
if ($MinScore !== false) {
$Discussions->where('Score >', $MinScore);
}
$Discussions = $Discussions->get()->result(DATASET_TYPE_ARRAY);
}
// Get matching Comments
$Comments = array();
if ($this->ShowComments()) {
$Comments = Gdn::sql()->select('c.*')->from('Comment c')->orderBy('DateInserted', 'DESC')->limit($this->Limit);
if ($MinScore !== false) {
$Comments->where('Score >', $MinScore);
}
$Comments = $Comments->get()->result(DATASET_TYPE_ARRAY);
$this->JoinCategory($Comments);
}
// Interleave
$Content = $this->Union('DateInserted', array('Discussion' => $Discussions, 'Comment' => $Comments));
$this->processContent($Content);
// Add result to cache
Gdn::cache()->store($SelectorScoreCacheKey, $Content, array(Gdn_Cache::FEATURE_EXPIRY => $this->Expiry));
}
$this->Security($Content);
$this->Condense($Content, $this->Limit);
return $Content;
}
示例14: query
/**
*
*
* @param string $Sql
* @param null $InputParameters
* @param array $Options
* @return Gdn_DataSet|object|string
*/
public function query($Sql, $InputParameters = null, $Options = array())
{
$Trace = debug_backtrace();
$Method = '';
foreach ($Trace as $Info) {
$Class = val('class', $Info, '');
if ($Class === '' || stringEndsWith($Class, 'Model', true) || stringEndsWith($Class, 'Plugin', true)) {
$Type = val('type', $Info, '');
$Method = $Class . $Type . $Info['function'] . '(' . self::formatArgs($Info['args']) . ')';
break;
}
}
// Save the query for debugging
// echo '<br />adding to queries: '.$Sql;
$Query = array('Sql' => $Sql, 'Parameters' => $InputParameters, 'Method' => $Method);
$SaveQuery = true;
if (isset($Options['Cache'])) {
$CacheKeys = (array) $Options['Cache'];
$Cache = array();
$AllSet = true;
foreach ($CacheKeys as $CacheKey) {
$Value = Gdn::cache()->get($CacheKey);
$CacheValue = $Value !== Gdn_Cache::CACHEOP_FAILURE;
$AllSet &= $CacheValue;
$Cache[$CacheKey] = $CacheValue;
}
$SaveQuery = !$AllSet;
$Query['Cache'] = $Cache;
}
// Start the Query Timer
$TimeStart = now();
$Result = parent::query($Sql, $InputParameters, $Options);
$Query = array_merge($this->LastInfo, $Query);
// Aggregate the query times
$TimeEnd = now();
$this->_ExecutionTime += $TimeEnd - $TimeStart;
if ($SaveQuery && !stringBeginsWith($Sql, 'set names')) {
$Query['Time'] = $TimeEnd - $TimeStart;
$this->_Queries[] = $Query;
}
return $Result;
}
示例15: gdn_statistics_tick_handler
/**
* Discussion view counter.
*
* @param $Sender
* @param $Args
*/
public function gdn_statistics_tick_handler($Sender, $Args)
{
$Path = Gdn::request()->post('Path');
$Args = Gdn::request()->post('Args');
parse_str($Args, $Args);
$ResolvedPath = trim(Gdn::request()->post('ResolvedPath'), '/');
$ResolvedArgs = Gdn::request()->post('ResolvedArgs');
$DiscussionID = null;
$DiscussionModel = new DiscussionModel();
// Comment permalink
if ($ResolvedPath == 'vanilla/discussion/comment') {
$CommentID = val('CommentID', $ResolvedArgs);
$CommentModel = new CommentModel();
$Comment = $CommentModel->getID($CommentID);
$DiscussionID = val('DiscussionID', $Comment);
} elseif ($ResolvedPath == 'vanilla/discussion/index') {
$DiscussionID = val('DiscussionID', $ResolvedArgs, null);
} elseif ($ResolvedPath == 'vanilla/discussion/embed') {
$ForeignID = val('vanilla_identifier', $Args);
if ($ForeignID) {
// This will be hit a lot so let's try caching it...
$Key = "DiscussionID.ForeignID.page.{$ForeignID}";
$DiscussionID = Gdn::cache()->get($Key);
if (!$DiscussionID) {
$Discussion = $DiscussionModel->getForeignID($ForeignID, 'page');
$DiscussionID = val('DiscussionID', $Discussion);
Gdn::cache()->store($Key, $DiscussionID, array(Gdn_Cache::FEATURE_EXPIRY, 1800));
}
}
}
if ($DiscussionID) {
$DiscussionModel->addView($DiscussionID);
}
}