本文整理汇总了PHP中cache_helper类的典型用法代码示例。如果您正苦于以下问题:PHP cache_helper类的具体用法?PHP cache_helper怎么用?PHP cache_helper使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了cache_helper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: instance
/**
* Returns an instance of the cache_helper.
*
* This is designed for internal use only and acts as a static store.
* @staticvar null $instance
* @return cache_helper
*/
protected static function instance()
{
if (is_null(self::$instance)) {
self::$instance = new cache_helper();
}
return self::$instance;
}
示例2: create_group
public static function create_group($group)
{
global $DB, $CFG;
// Valida os parametros.
$params = self::validate_parameters(self::create_group_parameters(), array('group' => $group));
// Transforma o array em objeto.
$group = (object) $group;
// Inicia a transacao, qualquer erro que aconteca o rollback sera executado.
$transaction = $DB->start_delegated_transaction();
// Busca o id do curso apartir do trm_id da turma.
$courseid = self::get_course_by_trm_id($group->trm_id);
// Se nao existir curso mapeado para a turma dispara uma excessao.
if (!$courseid) {
throw new Exception("Nenhum curso mapeado com a turma com trm_id: " . $group->trm_id);
}
$groupbyname = self::get_group_by_name($courseid, $group->name);
// Dispara uma excessao caso ja exista um grupo com o mesmo nome no mesmo curso
if ($groupbyname) {
throw new Exception("ja existe um grupo com o mesmo nome nessa turma trm_id: " . $group->trm_id);
}
$groupdata['courseid'] = $courseid;
$groupdata['name'] = $group->name;
$groupdata['description'] = $group->description;
$groupdata['descriptionformat'] = 1;
$groupdata['timecreated'] = time();
$groupdata['timemodified'] = $groupdata['timecreated'];
$resultid = $DB->insert_record('groups', $groupdata);
// Caso o curso tenha sido criado adiciona a tabela de controle os dados dos curso e da turma.
if ($resultid) {
$data['trm_id'] = $group->trm_id;
$data['grp_id'] = $group->grp_id;
$data['groupid'] = $resultid;
$res = $DB->insert_record('itg_grupo_group', $data);
// Busca as configuracoes do curso
$courseoptions = $DB->get_record('course', array('id' => $courseid), '*');
// Altera o formato de grupos do curso
$courseoptions->groupmode = 1;
$courseoptions->groupmodeforce = 1;
$DB->update_record('course', $courseoptions);
// Invalidate the grouping cache for the course
cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
// Prepara o array de retorno.
$returndata = null;
if ($res) {
$returndata['id'] = $resultid;
$returndata['status'] = 'success';
$returndata['message'] = 'Grupo criado com sucesso';
} else {
$returndata['id'] = 0;
$returndata['status'] = 'error';
$returndata['message'] = 'Erro ao tentar criar o grupo';
}
}
// Persiste as operacoes em caso de sucesso.
$transaction->allow_commit();
return $returndata;
}
示例3: cron_run
//.........这里部分代码省略.........
if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
require_once $CFG->dirroot . '/blog/lib.php';
// delete entries whose contextids no longer exists
mtrace("Deleting blog associations linked to non-existent contexts...", '');
cron_trace_time_and_memory();
$DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
mtrace('done.');
}
// Run question bank clean-up.
mtrace("Starting the question bank cron...", '');
cron_trace_time_and_memory();
require_once $CFG->libdir . '/questionlib.php';
question_bank::cron();
mtrace('done.');
//Run registration updated cron
mtrace(get_string('siteupdatesstart', 'hub'));
cron_trace_time_and_memory();
require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
$registrationmanager = new registration_manager();
$registrationmanager->cron();
mtrace(get_string('siteupdatesend', 'hub'));
// If enabled, fetch information about available updates and eventually notify site admins
if (empty($CFG->disableupdatenotifications)) {
$updateschecker = \core\update\checker::instance();
$updateschecker->cron();
}
//cleanup old session linked tokens
//deletes the session linked tokens that are over a day old.
mtrace("Deleting session linked tokens more than one day old...", '');
cron_trace_time_and_memory();
$DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
mtrace('done.');
// all other plugins
cron_execute_plugin_type('message', 'message plugins');
cron_execute_plugin_type('filter', 'filters');
cron_execute_plugin_type('editor', 'editors');
cron_execute_plugin_type('format', 'course formats');
cron_execute_plugin_type('profilefield', 'profile fields');
cron_execute_plugin_type('webservice', 'webservices');
cron_execute_plugin_type('repository', 'repository plugins');
cron_execute_plugin_type('qbehaviour', 'question behaviours');
cron_execute_plugin_type('qformat', 'question import/export formats');
cron_execute_plugin_type('qtype', 'question types');
cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
cron_execute_plugin_type('theme', 'themes');
cron_execute_plugin_type('tool', 'admin tools');
// and finally run any local cronjobs, if any
if ($locals = core_component::get_plugin_list('local')) {
mtrace('Processing customized cron scripts ...', '');
// new cron functions in lib.php first
cron_execute_plugin_type('local');
// legacy cron files are executed directly
foreach ($locals as $local => $localdir) {
if (file_exists("{$localdir}/cron.php")) {
include "{$localdir}/cron.php";
}
}
mtrace('done.');
}
mtrace('Running cache cron routines');
cache_helper::cron();
mtrace('done.');
// Run automated backups if required - these may take a long time to execute
require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
backup_cron_automated_helper::run_automated_backup();
// Run stats as at the end because they are known to take very long time on large sites
if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
require_once $CFG->dirroot . '/lib/statslib.php';
// check we're not before our runtime
$timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60;
if (time() > $timetocheck) {
// process configured number of days as max (defaulting to 31)
$maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
if (stats_cron_daily($maxdays)) {
if (stats_cron_weekly()) {
if (stats_cron_monthly()) {
stats_clean_old();
}
}
}
@set_time_limit(0);
} else {
mtrace('Next stats run after:' . userdate($timetocheck));
}
}
// Run badges review cron.
mtrace("Starting badges cron...");
require_once $CFG->dirroot . '/badges/cron.php';
badge_cron();
mtrace('done.');
// cleanup file trash - not very important
$fs = get_file_storage();
$fs->cron();
mtrace("Cron script completed correctly");
gc_collect_cycles();
mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
$difftime = microtime_diff($starttime, microtime());
mtrace("Execution took " . $difftime . " seconds");
}
示例4: set_many
/**
* Sends several key => value pairs to the cache.
*
* Using this function comes with potential performance implications.
* Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
* the equivalent singular method for each item provided.
* This should not deter you from using this function as there is a performance benefit in situations where the cache store
* does support it, but you should be aware of this fact.
*
* <code>
* // This code will add four entries to the cache, one for each url.
* $cache->set_many(array(
* 'main' => 'http://moodle.org',
* 'docs' => 'http://docs.moodle.org',
* 'tracker' => 'http://tracker.moodle.org',
* 'qa' => ''http://qa.moodle.net'
* ));
* </code>
*
* @param array $keyvaluearray An array of key => value pairs to send to the cache.
* @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
* ... if they care that is.
*/
public function set_many(array $keyvaluearray)
{
$this->check_tracked_user();
$loader = $this->get_loader();
if ($loader !== false) {
// We have a loader available set it there as well.
// We have to let the loader do its own parsing of data as it may be unique.
$loader->set_many($keyvaluearray);
}
$data = array();
$definitionid = $this->get_definition()->get_ttl();
$simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
foreach ($keyvaluearray as $key => $value) {
if (is_object($value) && $value instanceof cacheable_object) {
$value = new cache_cached_object($value);
} else {
if (!is_scalar($value)) {
// If data is an object it will be a reference.
// If data is an array if may contain references.
// We want to break references so that the cache cannot be modified outside of itself.
// Call the function to unreference it (in the best way possible).
$value = $this->unref($value);
}
}
if ($simulatettl) {
$value = new cache_ttl_wrapper($value, $definitionid);
}
$data[$key] = array('key' => $this->parse_key($key), 'value' => $value);
}
$successfullyset = $this->get_store()->set_many($data);
if ($this->perfdebug && $successfullyset) {
cache_helper::record_cache_set($this->storetype, $definitionid, $successfullyset);
}
return $successfullyset;
}
示例5: xmldb_main_upgrade
//.........这里部分代码省略.........
} else {
if (strpos($filter, 'filter/') === 0) {
$newfilters[] = substr($filter, 7);
}
}
}
$filters = implode(',', $newfilters);
set_config($config, $filters);
}
}
unset($tables);
unset($table);
unset($configs);
unset($newfilters);
unset($filters);
unset($filter);
// Main savepoint reached.
upgrade_main_savepoint(true, 2012123000.0);
}
if ($oldversion < 2013021100.01) {
// Make sure there are no bogus nulls in old MySQL tables.
$DB->set_field_select('user', 'password', '', "password IS NULL");
// Changing precision of field password on table user to (255).
$table = new xmldb_table('user');
$field = new xmldb_field('password', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'username');
// Launch change of precision for field password.
$dbman->change_field_precision($table, $field);
// Main savepoint reached.
upgrade_main_savepoint(true, 2013021100.01);
}
if ($oldversion < 2013021800.0) {
// Add the site identifier to the cache config's file.
$siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
cache_helper::update_site_identifier($siteidentifier);
// Main savepoint reached.
upgrade_main_savepoint(true, 2013021800.0);
}
if ($oldversion < 2013021801.0) {
// Fixing possible wrong MIME types for SMART Notebook files.
$extensions = array('%.gallery', '%.galleryitem', '%.gallerycollection', '%.nbk', '%.notebook', '%.xbk');
$select = $DB->sql_like('filename', '?', false);
foreach ($extensions as $extension) {
$DB->set_field_select('files', 'mimetype', 'application/x-smarttech-notebook', $select, array($extension));
}
upgrade_main_savepoint(true, 2013021801.0);
}
if ($oldversion < 2013021801.01) {
// This upgrade step is re-written under MDL-38228 (see below).
/*
// Retrieve the list of course_sections as a recordset to save memory
$coursesections = $DB->get_recordset('course_sections', null, 'course, id', 'id, course, sequence');
foreach ($coursesections as $coursesection) {
// Retrieve all of the actual modules in this course and section combination to reduce DB calls
$actualsectionmodules = $DB->get_records('course_modules',
array('course' => $coursesection->course, 'section' => $coursesection->id), '', 'id, section');
// Break out the current sequence so that we can compare it
$currentsequence = explode(',', $coursesection->sequence);
$newsequence = array();
// Check each of the modules in the current sequence
foreach ($currentsequence as $module) {
if (isset($actualsectionmodules[$module])) {
$newsequence[] = $module;
// We unset the actualsectionmodules so that we don't get duplicates and that we can add orphaned
// modules later
示例6: change_sortorder_by_one
/**
* Changes the sort order of this categories parent shifting this category up or down one.
*
* @global \moodle_database $DB
* @param bool $up If set to true the category is shifted up one spot, else its moved down.
* @return bool True on success, false otherwise.
*/
public function change_sortorder_by_one($up)
{
global $DB;
$params = array($this->sortorder, $this->parent);
if ($up) {
$select = 'sortorder < ? AND parent = ?';
$sort = 'sortorder DESC';
} else {
$select = 'sortorder > ? AND parent = ?';
$sort = 'sortorder ASC';
}
fix_course_sortorder();
$swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
$swapcategory = reset($swapcategory);
if ($swapcategory) {
$DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
$DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
$this->sortorder = $swapcategory->sortorder;
$event = \core\event\course_category_updated::create(array('objectid' => $this->id, 'context' => $this->get_context()));
$event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id, $this->id));
$event->trigger();
// Finally reorder courses.
fix_course_sortorder();
cache_helper::purge_by_event('changesincoursecat');
return true;
}
return false;
}
示例7: reset_dataroot
/**
* Purge dataroot directory
* @static
* @return void
*/
public static function reset_dataroot() {
global $CFG;
$childclassname = self::get_framework() . '_util';
$handle = opendir($CFG->dataroot);
while (false !== ($item = readdir($handle))) {
if (in_array($item, $childclassname::$datarootskiponreset)) {
continue;
}
if (is_dir("$CFG->dataroot/$item")) {
remove_dir("$CFG->dataroot/$item", false);
} else {
unlink("$CFG->dataroot/$item");
}
}
closedir($handle);
make_temp_directory('');
make_cache_directory('');
make_cache_directory('htmlpurifier');
// Reset the cache API so that it recreates it's required directories as well.
cache_factory::reset();
// Purge all data from the caches. This is required for consistency.
// Any file caches that happened to be within the data root will have already been clearer (because we just deleted cache)
// and now we will purge any other caches as well.
cache_helper::purge_all();
}
示例8: message_processor_uninstall
/**
* Uninstall a message processor
*
* @param string $name A message processor name like 'email', 'jabber'
*/
function message_processor_uninstall($name) {
global $DB;
$transaction = $DB->start_delegated_transaction();
$DB->delete_records('message_processors', array('name' => $name));
$DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
// delete permission preferences only, we do not care about loggedin/loggedoff
// defaults, they will be removed on the next attempt to update the preferences
$DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
$transaction->allow_commit();
// Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));
}
示例9: array
if ($movecourse = $DB->get_record('course', array('id' => $moveup))) {
$swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder - 1));
}
} else {
if ($movecourse = $DB->get_record('course', array('id' => $movedown))) {
$swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder + 1));
}
}
if ($swapcourse and $movecourse) {
// Check course's category.
if ($movecourse->category != $id) {
print_error('coursedoesnotbelongtocategory');
}
$DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $movecourse->id));
$DB->set_field('course', 'sortorder', $movecourse->sortorder, array('id' => $swapcourse->id));
cache_helper::purge_by_event('changesincourse');
add_to_log($movecourse->id, "course", "move", "edit.php?id=$movecourse->id", $movecourse->id);
}
}
// Prepare the standard URL params for this page. We'll need them later.
$urlparams = array('categoryid' => $id);
if ($page) {
$urlparams['page'] = $page;
}
if ($perpage) {
$urlparams['perpage'] = $perpage;
}
$urlparams += $searchcriteria;
$PAGE->set_pagelayout('coursecategory');
示例10: show
/**
* Show course category and restores visibility for child course and subcategories
*
* Note that there is no capability check inside this function
*
* This function does not update field course_categories.timemodified
* If you want to update timemodified, use
* $coursecat->update(array('visible' => 1));
*/
public function show()
{
if ($this->show_raw()) {
cache_helper::purge_by_event('changesincoursecat');
add_to_log(SITEID, "category", "show", "editcategory.php?id={$this->id}", $this->id);
}
}
示例11: reset_dataroot
/**
* Purge dataroot directory
* @static
* @return void
*/
public static function reset_dataroot()
{
global $CFG;
$childclassname = self::get_framework() . '_util';
// Do not delete automatically installed files.
self::skip_original_data_files($childclassname);
// Clear file status cache, before checking file_exists.
clearstatcache();
// Clean up the dataroot folder.
$handle = opendir(self::get_dataroot());
while (false !== ($item = readdir($handle))) {
if (in_array($item, $childclassname::$datarootskiponreset)) {
continue;
}
if (is_dir(self::get_dataroot() . "/{$item}")) {
remove_dir(self::get_dataroot() . "/{$item}", false);
} else {
unlink(self::get_dataroot() . "/{$item}");
}
}
closedir($handle);
// Clean up the dataroot/filedir folder.
if (file_exists(self::get_dataroot() . '/filedir')) {
$handle = opendir(self::get_dataroot() . '/filedir');
while (false !== ($item = readdir($handle))) {
if (in_array('filedir/' . $item, $childclassname::$datarootskiponreset)) {
continue;
}
if (is_dir(self::get_dataroot() . "/filedir/{$item}")) {
remove_dir(self::get_dataroot() . "/filedir/{$item}", false);
} else {
unlink(self::get_dataroot() . "/filedir/{$item}");
}
}
closedir($handle);
}
make_temp_directory('');
make_cache_directory('');
make_localcache_directory('');
// Reset the cache API so that it recreates it's required directories as well.
cache_factory::reset();
// Purge all data from the caches. This is required for consistency.
// Any file caches that happened to be within the data root will have already been clearer (because we just deleted cache)
// and now we will purge any other caches as well.
cache_helper::purge_all();
}
示例12: get_performance_info
//.........这里部分代码省略.........
$details .= "<div class='backtrace'>{$backtrace}</div>";
}
$details .= '</div>';
}
}
$info['html'] .= "<span class='includedyuimodules'>Included YUI modules: {$yuicount}</span> ";
$info['txt'] .= "includedyuimodules: {$yuicount} ";
$info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: {$othercount}</span> ";
$info['txt'] .= "includedjsmodules: {$othercount} ";
if ($details) {
$info['html'] .= '<div id="yui-module-debug" class="notifytiny">' . $details . '</div>';
}
}
if (!empty($PERF->logwrites)) {
$info['logwrites'] = $PERF->logwrites;
$info['html'] .= '<span class="logwrites">Log DB writes ' . $info['logwrites'] . '</span> ';
$info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' ';
}
$info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites);
$info['html'] .= '<span class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</span> ';
$info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' ';
if (function_exists('posix_times')) {
$ptimes = posix_times();
if (is_array($ptimes)) {
foreach ($ptimes as $key => $val) {
$info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
}
$info['html'] .= "<span class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</span> ";
$info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} ";
}
}
// Grab the load average for the last minute.
// /proc will only work under some linux configurations
// while uptime is there under MacOSX/Darwin and other unices.
if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) {
list($serverload) = explode(' ', $loadavg[0]);
unset($loadavg);
} else {
if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) {
if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) {
$serverload = $matches[1];
} else {
trigger_error('Could not parse uptime output!');
}
}
}
if (!empty($serverload)) {
$info['serverload'] = $serverload;
$info['html'] .= '<span class="serverload">Load average: ' . $info['serverload'] . '</span> ';
$info['txt'] .= "serverload: {$info['serverload']} ";
}
// Display size of session if session started.
if ($si = \core\session\manager::get_performance_info()) {
$info['sessionsize'] = $si['size'];
$info['html'] .= $si['html'];
$info['txt'] .= $si['txt'];
}
if ($stats = cache_helper::get_stats()) {
$html = '<span class="cachesused">';
$html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
$text = 'Caches used (hits/misses/sets): ';
$hits = 0;
$misses = 0;
$sets = 0;
foreach ($stats as $definition => $stores) {
$html .= '<span class="cache-definition-stats">';
$html .= '<span class="cache-definition-stats-heading">' . $definition . '</span>';
$text .= "{$definition} {";
foreach ($stores as $store => $data) {
$hits += $data['hits'];
$misses += $data['misses'];
$sets += $data['sets'];
if ($data['hits'] == 0 and $data['misses'] > 0) {
$cachestoreclass = 'nohits';
} else {
if ($data['hits'] < $data['misses']) {
$cachestoreclass = 'lowhits';
} else {
$cachestoreclass = 'hihits';
}
}
$text .= "{$store}({$data['hits']}/{$data['misses']}/{$data['sets']}) ";
$html .= "<span class=\"cache-store-stats {$cachestoreclass}\">{$store}: {$data['hits']} / {$data['misses']} / {$data['sets']}</span>";
}
$html .= '</span>';
$text .= '} ';
}
$html .= "<span class='cache-total-stats'>Total: {$hits} / {$misses} / {$sets}</span>";
$html .= '</span> ';
$info['cachesused'] = "{$hits} / {$misses} / {$sets}";
$info['html'] .= $html;
$info['txt'] .= $text . '. ';
} else {
$info['cachesused'] = '0 / 0 / 0';
$info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
$info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
}
$info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>';
return $info;
}
示例13: stdClass
}
$newgroup = new stdClass();
$newgroup->courseid = $data->courseid;
$newgroup->name = $group['name'];
$groupid = groups_create_group($newgroup);
$createdgroups[] = $groupid;
foreach ($group['members'] as $user) {
groups_add_member($groupid, $user->id);
}
if ($grouping) {
// Ask this function not to invalidate the cache, we'll do that manually once at the end.
groups_assign_grouping($grouping->id, $groupid, null, false);
}
}
// Invalidate the course groups cache seeing as we've changed it.
cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
if ($failed) {
foreach ($createdgroups as $groupid) {
groups_delete_group($groupid);
}
if ($createdgrouping) {
groups_delete_grouping($createdgrouping);
}
} else {
redirect($returnurl);
}
}
}
$PAGE->navbar->add($strparticipants, new moodle_url('/user/index.php', array('id' => $courseid)));
$PAGE->navbar->add($strgroups, new moodle_url('/group/index.php', array('id' => $courseid)));
$PAGE->navbar->add($strautocreategroups);
示例14: create_cache
/**
* Common public method to create a cache instance given a definition.
*
* This is used by the static make methods.
*
* @param cache_definition $definition
* @return cache_application|cache_session|cache_store
* @throws coding_exception
*/
public function create_cache(cache_definition $definition)
{
$class = $definition->get_cache_class();
$stores = cache_helper::get_stores_suitable_for_definition($definition);
foreach ($stores as $key => $store) {
if (!$store::are_requirements_met()) {
unset($stores[$key]);
}
}
if (count($stores) === 0) {
// Hmm still no stores, better provide a dummy store to mimic functionality. The dev will be none the wiser.
$stores[] = $this->create_dummy_store($definition);
}
$loader = null;
if ($definition->has_data_source()) {
$loader = $definition->get_data_source();
}
while (($store = array_pop($stores)) !== null) {
$loader = new $class($definition, $store, $loader);
}
return $loader;
}
示例15: get_performance_info
//.........这里部分代码省略.........
}
$info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites);
$info['html'] .= '<li class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</li> ';
$info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' ';
$info['dbtime'] = round($DB->perf_get_queries_time(), 5);
$info['html'] .= '<li class="dbtime">DB queries time: ' . $info['dbtime'] . ' secs</li> ';
$info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
if (function_exists('posix_times')) {
$ptimes = posix_times();
if (is_array($ptimes)) {
foreach ($ptimes as $key => $val) {
$info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
}
$info['html'] .= "<li class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</li> ";
$info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} ";
}
}
// Grab the load average for the last minute.
// /proc will only work under some linux configurations
// while uptime is there under MacOSX/Darwin and other unices.
if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) {
list($serverload) = explode(' ', $loadavg[0]);
unset($loadavg);
} else {
if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) {
if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) {
$serverload = $matches[1];
} else {
trigger_error('Could not parse uptime output!');
}
}
}
if (!empty($serverload)) {
$info['serverload'] = $serverload;
$info['html'] .= '<li class="serverload">Load average: ' . $info['serverload'] . '</li> ';
$info['txt'] .= "serverload: {$info['serverload']} ";
}
// Display size of session if session started.
if ($si = \core\session\manager::get_performance_info()) {
$info['sessionsize'] = $si['size'];
$info['html'] .= $si['html'];
$info['txt'] .= $si['txt'];
}
if ($stats = cache_helper::get_stats()) {
$html = '<ul class="cachesused list-unstyled m-l-1">';
$html .= '<li class="cache-stats-heading">Caches used (hits/misses/sets)</li>';
$text = 'Caches used (hits/misses/sets): ';
$hits = 0;
$misses = 0;
$sets = 0;
foreach ($stats as $definition => $details) {
switch ($details['mode']) {
case cache_store::MODE_APPLICATION:
$modeclass = 'application';
$mode = ' <span title="application cache">[a]</span>';
break;
case cache_store::MODE_SESSION:
$modeclass = 'session';
$mode = ' <span title="session cache">[s]</span>';
break;
case cache_store::MODE_REQUEST:
$modeclass = 'request';
$mode = ' <span title="request cache">[r]</span>';
break;
}
$html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-' . $modeclass . '">';
$html .= '<li class="cache-definition-stats-heading p-t-1">' . $definition . $mode . '</li>';
$text .= "{$definition} {";
foreach ($details['stores'] as $store => $data) {
$hits += $data['hits'];
$misses += $data['misses'];
$sets += $data['sets'];
if ($data['hits'] == 0 and $data['misses'] > 0) {
$cachestoreclass = 'nohits text-danger';
} else {
if ($data['hits'] < $data['misses']) {
$cachestoreclass = 'lowhits text-warning';
} else {
$cachestoreclass = 'hihits text-success';
}
}
$text .= "{$store}({$data['hits']}/{$data['misses']}/{$data['sets']}) ";
$html .= "<li class=\"cache-store-stats {$cachestoreclass}\">{$store}: {$data['hits']} / {$data['misses']} / {$data['sets']}</li>";
}
$html .= '</ul>';
$text .= '} ';
}
$html .= '</ul> ';
$html .= "<div class='cache-total-stats row'>Total: {$hits} / {$misses} / {$sets}</div>";
$info['cachesused'] = "{$hits} / {$misses} / {$sets}";
$info['html'] .= $html;
$info['txt'] .= $text . '. ';
} else {
$info['cachesused'] = '0 / 0 / 0';
$info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
$info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
}
$info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>';
return $info;
}