本文整理汇总了PHP中Gdn::Cache方法的典型用法代码示例。如果您正苦于以下问题:PHP Gdn::Cache方法的具体用法?PHP Gdn::Cache怎么用?PHP Gdn::Cache使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Gdn
的用法示例。
在下文中一共展示了Gdn::Cache方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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;
}
示例2: GetInteractionRules
/**
* This checks the cache for current rule set that can be triggered for a user
* by another user. It loads all rules and selects only those that return true
* on its `Interacts()` method.
*
* @return array Rules that are currently available to use that are interactive.
*/
public static function GetInteractionRules()
{
$Rules = Gdn::Cache()->Get('Yaga.Badges.InteractionRules');
if ($Rules === Gdn_Cache::CACHEOP_FAILURE) {
$AllRules = RulesController::GetRules();
$TempRules = array();
foreach ($AllRules as $ClassName => $Name) {
$Rule = new $ClassName();
if ($Rule->Interacts()) {
$TempRules[$ClassName] = $Name;
}
}
if (empty($TempRules)) {
$Rules = serialize(FALSE);
} else {
$Rules = serialize($TempRules);
}
Gdn::Cache()->Store('Yaga.Badges.InteractionRules', $Rules, array(Gdn_Cache::FEATURE_EXPIRY => C('Yaga.Rules.CacheExpire', 86400)));
}
return unserialize($Rules);
}
示例3: 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()) {
$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();
}
}
示例4: Save
/**
* Saves all settings in $Group to $File.
*
* @param string $File The full path to the file where the Settings should be saved.
* @param string $Group The name of the settings group to be saved to the $File.
* @param boolean $RequireSourceFile Should $File be required to exist in order to save? If true, then values
* from this file will be merged into the settings array before it is saved.
* If false, the values in the settings array will overwrite any values
* existing in the file (if it exists).
* @return boolean
*/
public function Save($File = '', $Group = '', $RequireSourceFile = TRUE)
{
if ($File == '') {
$File = $this->_File;
}
if ($File == '') {
trigger_error(ErrorMessage('You must specify a file path to be saved.', 'Configuration', 'Save'), E_USER_ERROR);
}
if (!is_writable($File)) {
throw new Exception(sprintf(T("Unable to write to config file '%s' when saving."), $File));
}
if ($Group == '') {
$Group = $this->CurrentGroup;
}
if ($Group == '') {
$Group = 'Configuration';
}
$Data =& $this->_SaveData;
$this->_Sort($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 ($File == PATH_LOCAL_CONF . '/config.php') {
if (!isset($Data['Database'])) {
if ($Pm = Gdn::PluginManager()) {
$Pm->EventArguments['Data'] = $Data;
$Pm->EventArguments['Backtrace'] = debug_backtrace();
$Pm->FireEvent('ConfigError');
}
$this->_SaveData = array();
$this->_File = '';
return FALSE;
}
}
$NewLines = array();
$NewLines[] = "<?php if (!defined('APPLICATION')) exit();";
$LastName = '';
foreach ($Data as $Name => $Value) {
// Write a newline to seperate sections.
if ($LastName != $Name && is_array($Value)) {
$NewLines[] = '';
$NewLines[] = '// ' . $Name;
}
$Line = "\$" . $Group . "['" . $Name . "']";
FormatArrayAssignment($NewLines, $Line, $Value);
}
// Record who made the change and when
if (is_array($NewLines)) {
$Session = Gdn::Session();
$User = $Session->UserID > 0 && is_object($Session->User) ? $Session->User->Name : 'Unknown';
$NewLines[] = '';
$NewLines[] = '// Last edited by ' . $User . ' (' . RemoteIp() . ')' . Gdn_Format::ToDateTime();
}
$FileContents = FALSE;
if ($NewLines !== FALSE) {
$FileContents = implode("\n", $NewLines);
}
if ($FileContents === FALSE) {
trigger_error(ErrorMessage('Failed to define configuration file contents.', 'Configuration', 'Save'), E_USER_ERROR);
}
$FileKey = sprintf(self::CONFIG_FILE_CACHE_KEY, $File);
if ($this->Caching() && Gdn::Cache()->Type() == Gdn_Cache::CACHE_TYPE_MEMORY && Gdn::Cache()->ActiveEnabled()) {
$CachedConfigData = Gdn::Cache()->Store($FileKey, $Data, array(Gdn_Cache::FEATURE_NOPREFIX => TRUE));
}
// Infrastructure deployment. Use old method.
if (PATH_LOCAL_CONF != PATH_CONF) {
$Result = Gdn_FileSystem::SaveFile($File, $FileContents, LOCK_EX);
} else {
$TmpFile = tempnam(PATH_CONF, 'config');
$Result = FALSE;
if (file_put_contents($TmpFile, $FileContents) !== FALSE) {
chmod($TmpFile, 0775);
$Result = rename($TmpFile, $File);
}
}
if ($Result && function_exists('apc_delete_file')) {
// This fixes a bug with some configurations of apc.
@apc_delete_file($File);
}
// Clear out the save data array
$this->_SaveData = array();
$this->_File = '';
return $Result;
}
示例5: ClearThemeCache
public function ClearThemeCache($SearchPaths = NULL)
{
if (!is_null($SearchPaths)) {
if (!is_array($SearchPaths)) {
$SearchPaths = array($SearchPaths);
}
} else {
$SearchPaths = $this->SearchPaths();
}
foreach ($SearchPaths as $SearchPath => $SearchPathName) {
$SearchPathCacheKey = "Garden.Themes.PathCache.{$SearchPath}";
$SearchPathCache = Gdn::Cache()->Remove($SearchPathCacheKey, array(Gdn_Cache::FEATURE_NOPREFIX => TRUE));
}
}
示例6: Fallback
/**
*
*
* @param type $Key Cache key
* @param type $Options
* @return mixed
*/
protected function Fallback($Key, $Options)
{
$Fallback = GetValue(Gdn_Cache::FEATURE_FALLBACK, $Options, NULL);
if (is_null($Fallback)) {
return Gdn_Cache::CACHEOP_FAILURE;
}
$FallbackType = array_shift($Fallback);
switch ($FallbackType) {
case 'query':
$QueryFallbackField = array_shift($Fallback);
$QueryFallbackCode = array_shift($Fallback);
$FallbackResult = Gdn::Database()->Query($QueryFallbackCode);
if ($FallbackResult->NumRows()) {
if (!is_null($QueryFallbackField)) {
$FallbackResult = GetValue($QueryFallbackField, $FallbackResult->FirstRow(DATASET_TYPE_ARRAY));
} else {
$FallbackResult = $FallbackResult->ResultArray();
}
}
break;
case 'callback':
$CallbackFallbackMethod = array_shift($Fallback);
$CallbackFallbackArgs = $Fallback;
$FallbackResult = call_user_func_array($CallbackFallbackMethod, $CallbackFallbackArgs);
break;
}
Gdn::Cache()->Store($Key, $FallbackResult);
return $FallbackResult;
}
示例7: Save
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 = ArrayValue('Location', $FormPostValues, '');
if ($Location != '') {
$Location = explode('/', $Location);
$Application = GetValue(0, $Location, '');
if (in_array($Application, $this->_SpecialLocations)) {
$FormPostValues['Application'] = NULL;
$FormPostValues['Controller'] = $Application;
$FormPostValues['Method'] = NULL;
} else {
$FormPostValues['Application'] = $Application;
$FormPostValues['Controller'] = GetValue(1, $Location, '');
$FormPostValues['Method'] = GetValue(2, $Location, '');
}
}
Gdn::Cache()->Remove('Messages');
return parent::Save($FormPostValues, $Settings);
}
示例8: Ping
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();
}
示例9: GetUnansweredCount
public function GetUnansweredCount()
{
$Count = Gdn::Cache()->Get('QnA-UnansweredCount');
if ($Count === Gdn_Cache::CACHEOP_FAILURE) {
Gdn::SQL()->WhereIn('QnA', array('Unanswered', 'Rejected'));
$Count = Gdn::SQL()->GetCount('Discussion', array('Type' => 'Question'));
Gdn::Cache()->Store('QnA-UnansweredCount', $Count, array(Gdn_Cache::FEATURE_EXPIRY => 15 * 60));
}
return $Count;
}
示例10: htmlspecialchars
<div id="Sql" class="DebugInfo">
<h2>Debug Information</h2>
<?php
// Add the canonical Url.
if (method_exists($Sender, 'CanonicalUrl')) {
$CanonicalUrl = htmlspecialchars($Sender->CanonicalUrl(), ENT_COMPAT, 'UTF-8');
echo '<div class="CanonicalUrl"><b>' . T('Canonical Url') . "</b>: <a href=\"{$CanonicalUrl}\" accesskey=\"r\">{$CanonicalUrl}</a></div>";
}
?>
<?php
// Add some cache info.
if (Gdn::Cache()->ActiveEnabled()) {
echo '<h3>Cache Information</h3>';
echo '<pre>';
echo '<b>Cache Revision</b>: ' . Gdn::Cache()->GetRevision() . "\n";
echo '<b>Permissions Revision</b>: ' . Gdn::UserModel()->GetPermissionsIncrement() . "\n";
if (property_exists('Gdn_Cache', 'GetCount')) {
echo '<b>Cache Gets</b>: ' . sprintf('%s in %ss', Gdn_Cache::$GetCount, Gdn_Cache::$GetTime);
}
echo '</pre>';
if (property_exists('Gdn_Cache', 'trackGet') && sizeof(Gdn_Cache::$trackGet)) {
uasort(Gdn_Cache::$trackGet, function ($a, $b) {
return $b['hits'] - $a['hits'];
});
$numKeys = sizeof(Gdn_Cache::$trackGet);
$duplicateGets = 0;
$wastedBytes = 0;
$totalBytes = 0;
foreach (Gdn_Cache::$trackGet as $key => $keyData) {
if ($keyData['hits'] > 1) {
示例11: GetRecent
/**
* Returns a list of all recent scored posts ordered by highest score
*
* @param string $Timespan strtotime compatible time
* @param int $Limit
* @param int $Offset
* @return array
*/
public function GetRecent($Timespan = 'week', $Limit = NULL, $Offset = 0)
{
$CacheKey = "yaga.best.last.{$Timespan}";
$Content = Gdn::Cache()->Get($CacheKey);
if ($Content == Gdn_Cache::CACHEOP_FAILURE) {
$TargetDate = date('Y-m-d H:i:s', strtotime("1 {$Timespan} ago"));
$SQL = $this->_BaseSQL('Discussion');
$Discussions = $SQL->Where('d.DateUpdated >', $TargetDate)->Get()->Result(DATASET_TYPE_ARRAY);
$SQL = $this->_BaseSQL('Comment');
$Comments = $SQL->Where('c.DateUpdated >', $TargetDate)->Get()->Result(DATASET_TYPE_ARRAY);
$this->JoinCategory($Comments);
// Interleave
$Content = $this->Union('Score', array('Discussion' => $Discussions, 'Comment' => $Comments));
$this->Prepare($Content);
Gdn::Cache()->Store($CacheKey, $Content, array(Gdn_Cache::FEATURE_EXPIRY => $this->_Expiry));
}
$this->Security($Content);
$this->Condense($Content, $Limit, $Offset);
return $Content;
}
示例12: 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)
{
if (C('Vanilla.Views.Denormalize', FALSE) && Gdn::Cache()->ActiveEnabled()) {
$CacheKey = "QueryCache.Discussion.{$DiscussionID}.CountViews";
// Increment. If not success, create key.
$Views = Gdn::Cache()->Increment($CacheKey);
if ($Views === Gdn_Cache::CACHEOP_FAILURE) {
$Views = $this->GetWhere(array('DiscussionID' => $DiscussionID))->Value('CountViews', 0);
Gdn::Cache()->Store($CacheKey, $Views);
}
// Every X views, writeback to Discussions
if ($Views % C('Vanilla.Views.DenormalizeWriteback', 100) == 0) {
$this->SetField($DiscussionID, 'CountViews', $Views);
}
} else {
$this->SQL->Update('Discussion')->Set('CountViews', 'CountViews + 1', FALSE)->Where('DiscussionID', $DiscussionID)->Put();
}
}
示例13: GetOperationCount
/**
* Wrapper for GetCountWhere that takes care of caching specific operation counts.
* @param string $Operation Comma-delimited list of operation types to get (sum of) counts for.
*/
public function GetOperationCount($Operation)
{
if ($Operation == 'edits') {
$Operation = array('edit', 'delete');
} else {
$Operation = explode(',', $Operation);
}
sort($Operation);
array_map('ucfirst', $Operation);
$CacheKey = 'Moderation.LogCount.' . implode('.', $Operation);
$Count = Gdn::Cache()->Get($CacheKey);
if ($Count === Gdn_Cache::CACHEOP_FAILURE) {
$Count = $this->GetCountWhere(array('Operation' => $Operation));
Gdn::Cache()->Store($CacheKey, $Count, array(Gdn_Cache::FEATURE_EXPIRY => 300));
}
return $Count;
}
示例14: Module
public static function Module($Name, $Properties = array())
{
if (isset($Properties['cache'])) {
$Key = isset($Properties['cachekey']) ? $Properties['cachekey'] : 'module.' . $Name;
$Result = Gdn::Cache()->Get($Key);
if ($Result !== Gdn_Cache::CACHEOP_FAILURE) {
// Trace('Module: '.$Result, $Key);
return $Result;
}
}
try {
if (!class_exists($Name)) {
if (Debug()) {
$Result = "Error: {$Name} doesn't exist";
} else {
$Result = "<!-- Error: {$Name} doesn't exist -->";
}
} else {
$Module = new $Name(Gdn::Controller(), '');
$Module->Visible = TRUE;
// Add properties passed in from the controller.
$ControllerProperties = Gdn::Controller()->Data('_properties.' . strtolower($Name), array());
$Properties = array_merge($ControllerProperties, $Properties);
foreach ($Properties as $Name => $Value) {
$Module->{$Name} = $Value;
}
$Result = $Module->ToString();
}
} catch (Exception $Ex) {
if (Debug()) {
$Result = '<pre class="Exception">' . htmlspecialchars($Ex->getMessage() . "\n" . $Ex->getTraceAsString()) . '</pre>';
} else {
$Result = $Ex->getMessage();
}
}
if (isset($Key)) {
// Trace($Result, "Store $Key");
Gdn::Cache()->Store($Key, $Result, array(Gdn_Cache::FEATURE_EXPIRY => $Properties['cache']));
}
return $Result;
}
示例15: Query
public function Query($Sql, $InputParameters = NULL, $Options = array())
{
$Trace = debug_backtrace();
$Method = '';
foreach ($Trace as $Info) {
$Class = GetValue('class', $Info, '');
if ($Class === '' || StringEndsWith($Class, 'Model', TRUE) || StringEndsWith($Class, 'Plugin', TRUE)) {
$Type = ArrayValue('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);
// 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;
}