本文整理汇总了PHP中Drupal::cache方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::cache方法的具体用法?PHP Drupal::cache怎么用?PHP Drupal::cache使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal
的用法示例。
在下文中一共展示了Drupal::cache方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: cacheGet
/**
* {@inheritdoc}
*/
public function cacheGet($type)
{
if ($type != 'results') {
return parent::cacheGet($type);
}
// Values to set: $view->result, $view->total_rows, $view->execute_time,
// $view->current_page.
if ($cache = \Drupal::cache($this->resultsBin)->get($this->generateResultsKey())) {
$cutoff = $this->cacheExpire($type);
if (!$cutoff || $cache->created > $cutoff) {
$this->view->result = $cache->data['result'];
$this->view->total_rows = $cache->data['total_rows'];
$this->view->setCurrentPage($cache->data['current_page']);
$this->view->execute_time = 0;
// Trick Search API into believing a search happened, to make faceting
// et al. work.
/** @var \Drupal\search_api\Query\ResultSetInterface $results */
$results = $cache->data['search_api results'];
/** @var \Drupal\search_api\Query\ResultsCacheInterface $static_results_cache */
$static_results_cache = \Drupal::service('search_api.results_static_cache');
$static_results_cache->addResults($results);
try {
$this->getQuery()->setSearchApiResults($results);
$this->getQuery()->setSearchApiQuery($results->getQuery());
} catch (SearchApiException $e) {
// Ignore.
}
return TRUE;
}
}
return FALSE;
}
示例2: __construct
/**
* Constructs a TwigEnvironment object and stores cache and storage
* internally.
*/
public function __construct(\Twig_LoaderInterface $loader = NULL, $options = array(), ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler)
{
// @todo Pass as arguments from the DIC.
$this->cache_object = \Drupal::cache();
// Ensure that twig.engine is loaded, given that it is needed to render a
// template because functions like twig_drupal_escape_filter are called.
require_once DRUPAL_ROOT . '/core/themes/engines/twig/twig.engine';
// Set twig path namespace for themes and modules.
$namespaces = array();
foreach ($module_handler->getModuleList() as $name => $extension) {
$namespaces[$name] = $extension->getPath();
}
foreach ($theme_handler->listInfo() as $name => $extension) {
$namespaces[$name] = $extension->getPath();
}
foreach ($namespaces as $name => $path) {
$templatesDirectory = $path . '/templates';
if (file_exists($templatesDirectory)) {
$loader->addPath($templatesDirectory, $name);
}
}
$this->templateClasses = array();
$this->stringLoader = new \Twig_Loader_String();
parent::__construct($loader, $options);
}
示例3: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
drupal_set_message('Settings saved');
$this->configFactory()->getEditable('itk_instagram_hashtag.settings')->set('itk_instagram_hashtag.client_id', $form_state->getValue('client_id'))->set('itk_instagram_hashtag.resolution', $form_state->getValue('resolution'))->set('itk_instagram_hashtag.sort_by', $form_state->getValue('sort_by'))->set('itk_instagram_hashtag.limit', $form_state->getValue('limit'))->set('itk_instagram_hashtag.enable_caption', $form_state->getValue('enable_caption'))->save();
// Make sure the new settings are available to the js.
\Drupal::cache('render')->deleteAll();
}
示例4: testPathCache
/**
* Tests the path cache.
*/
function testPathCache()
{
// Create test node.
$node1 = $this->drupalCreateNode();
// Create alias.
$edit = array();
$edit['source'] = '/node/' . $node1->id();
$edit['alias'] = '/' . $this->randomMachineName(8);
$this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
// Check the path alias whitelist cache.
$whitelist = \Drupal::cache()->get('path_alias_whitelist');
$this->assertTrue($whitelist->data['node']);
$this->assertFalse($whitelist->data['admin']);
// Visit the system path for the node and confirm a cache entry is
// created.
\Drupal::cache('data')->deleteAll();
// Make sure the path is not converted to the alias.
$this->drupalGet(trim($edit['source'], '/'), array('alias' => TRUE));
$this->assertTrue(\Drupal::cache('data')->get('preload-paths:' . $edit['source']), 'Cache entry was created.');
// Visit the alias for the node and confirm a cache entry is created.
\Drupal::cache('data')->deleteAll();
// @todo Remove this once https://www.drupal.org/node/2480077 lands.
Cache::invalidateTags(['rendered']);
$this->drupalGet(trim($edit['alias'], '/'));
$this->assertTrue(\Drupal::cache('data')->get('preload-paths:' . $edit['source']), 'Cache entry was created.');
}
示例5: testRaceCondition
/**
* Tests the behavior of the theme registry class.
*/
function testRaceCondition()
{
// The theme registry is not marked as persistable in case we don't have a
// proper request.
\Drupal::request()->setMethod('GET');
$cid = 'test_theme_registry';
// Directly instantiate the theme registry, this will cause a base cache
// entry to be written in __construct().
$cache = \Drupal::cache();
$lock_backend = \Drupal::lock();
$registry = new ThemeRegistry($cid, $cache, $lock_backend, array('theme_registry'), $this->container->get('module_handler')->isLoaded());
$this->assertTrue(\Drupal::cache()->get($cid), 'Cache entry was created.');
// Trigger a cache miss for an offset.
$this->assertTrue($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry.');
// This will cause the ThemeRegistry class to write an updated version of
// the cache entry when it is destroyed, usually at the end of the request.
// Before that happens, manually delete the cache entry we created earlier
// so that the new entry is written from scratch.
\Drupal::cache()->delete($cid);
// Destroy the class so that it triggers a cache write for the offset.
$registry->destruct();
$this->assertTrue(\Drupal::cache()->get($cid), 'Cache entry was created.');
// Create a new instance of the class. Confirm that both the offset
// requested previously, and one that has not yet been requested are both
// available.
$registry = new ThemeRegistry($cid, $cache, $lock_backend, array('theme_registry'), $this->container->get('module_handler')->isLoaded());
$this->assertTrue($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry');
$this->assertTrue($registry->get('theme_test_template_test_2'), 'Offset was returned correctly from the theme registry');
}
示例6: assertPageCacheContextsAndTags
/**
* Asserts page cache miss, then hit for the given URL; checks cache headers.
*
* @param \Drupal\Core\Url $url
* The URL to test.
* @param string[] $expected_contexts
* The expected cache contexts for the given URL.
* @param string[] $expected_tags
* The expected cache tags for the given URL.
*/
protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)
{
$absolute_url = $url->setAbsolute()->toString();
sort($expected_contexts);
sort($expected_tags);
// Assert cache miss + expected cache contexts + tags.
$this->drupalGet($absolute_url);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$this->assertCacheTags($expected_tags);
$this->assertCacheContexts($expected_contexts);
// Assert cache hit + expected cache contexts + tags.
$this->drupalGet($absolute_url);
$this->assertCacheTags($expected_tags);
$this->assertCacheContexts($expected_contexts);
// Assert page cache item + expected cache tags.
$cid_parts = array($url->setAbsolute()->toString(), 'html');
$cid = implode(':', $cid_parts);
$cache_entry = \Drupal::cache('render')->get($cid);
sort($cache_entry->tags);
$this->assertEqual($cache_entry->tags, $expected_tags);
if ($cache_entry->tags !== $expected_tags) {
debug('Missing cache tags: ' . implode(',', array_diff($cache_entry->tags, $expected_tags)));
debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $cache_entry->tags)));
}
}
示例7: update_selection_page
/**
* Renders a form with a list of available database updates.
*/
function update_selection_page()
{
// Make sure there is no stale theme registry.
\Drupal::cache()->deleteAll();
$build = \Drupal::formBuilder()->getForm('Drupal\\Core\\Update\\Form\\UpdateScriptSelectionForm');
$build['#title'] = 'Drupal database update';
return $build;
}
示例8: assertViewsCacheTags
/**
* Asserts a view's result & render cache items' cache tags.
*
* This methods uses a full view object in order to render the view.
*
* @param \Drupal\views\ViewExecutable $view
* The view to test, must have caching enabled.
* @param null|string[] $expected_results_cache
* NULL when expecting no results cache item, a set of cache tags expected
* to be set on the results cache item otherwise.
* @param bool $views_caching_is_enabled
* Whether to expect an output cache item. If TRUE, the cache tags must
* match those in $expected_render_array_cache_tags.
* @param string[] $expected_render_array_cache_tags
* A set of cache tags expected to be set on the built view's render array.
*
* @return array
* The render array.
*/
protected function assertViewsCacheTags(ViewExecutable $view, $expected_results_cache, $views_caching_is_enabled, array $expected_render_array_cache_tags)
{
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
/** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
$render_cache = \Drupal::service('render_cache');
$build = $view->buildRenderable();
$original = $build;
// Ensure the current request is a GET request so that render caching is
// active for direct rendering of views, just like for actual requests.
/** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
$request_stack = \Drupal::service('request_stack');
$request = new Request();
$request->server->set('REQUEST_TIME', REQUEST_TIME);
$view->setRequest($request);
$request_stack->push($request);
$renderer->renderRoot($build);
// Render array cache tags.
$this->pass('Checking render array cache tags.');
sort($expected_render_array_cache_tags);
$this->assertEqual($build['#cache']['tags'], $expected_render_array_cache_tags);
$this->debugCacheTags($build['#cache']['tags'], $expected_render_array_cache_tags);
if ($views_caching_is_enabled) {
$this->pass('Checking Views results cache item cache tags.');
/** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
$cache_plugin = $view->display_handler->getPlugin('cache');
// Results cache.
// Ensure that the views query is built.
$view->build();
$results_cache_item = \Drupal::cache('data')->get($cache_plugin->generateResultsKey());
if (is_array($expected_results_cache)) {
$this->assertTrue($results_cache_item, 'Results cache item found.');
if ($results_cache_item) {
sort($expected_results_cache);
$this->assertEqual($results_cache_item->tags, $expected_results_cache);
$this->debugCacheTags($results_cache_item->tags, $expected_results_cache);
}
} else {
$this->assertFalse($results_cache_item, 'Results cache item not found.');
}
$this->pass('Checking Views render cache item cache tags.');
$original['#cache'] += ['contexts' => []];
$original['#cache']['contexts'] = Cache::mergeContexts($original['#cache']['contexts'], $this->container->getParameter('renderer.config')['required_cache_contexts']);
$render_cache_item = $render_cache->get($original);
if ($views_caching_is_enabled === TRUE) {
$this->assertTrue(!empty($render_cache_item), 'Render cache item found.');
if ($render_cache_item) {
$this->assertEqual($render_cache_item['#cache']['tags'], $expected_render_array_cache_tags);
$this->debugCacheTags($render_cache_item['#cache']['tags'], $expected_render_array_cache_tags);
}
} else {
$this->assertFalse($render_cache_item, 'Render cache item not found.');
}
}
$view->destroy();
$request_stack->pop();
return $build;
}
示例9: assertCacheRemoved
/**
* Asserts that a cache entry has been removed.
*
* @param $message
* Message to display.
* @param $cid
* The cache id.
* @param $bin
* The bin the cache item was stored in.
*/
function assertCacheRemoved($message, $cid = NULL, $bin = NULL)
{
if ($bin == NULL) {
$bin = $this->defaultBin;
}
if ($cid == NULL) {
$cid = $this->defaultCid;
}
$cached = \Drupal::cache($bin)->get($cid);
$this->assertFalse($cached, $message);
}
示例10: assertPageCacheContextsAndTags
/**
* Asserts page cache miss, then hit for the given URL; checks cache headers.
*
* @param \Drupal\Core\Url $url
* The URL to test.
* @param string[] $expected_contexts
* The expected cache contexts for the given URL.
* @param string[] $expected_tags
* The expected cache tags for the given URL.
*/
protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)
{
$absolute_url = $url->setAbsolute()->toString();
sort($expected_contexts);
sort($expected_tags);
$get_cache_header_values = function ($header_name) {
$header_value = $this->drupalGetHeader($header_name);
if (empty($header_value)) {
return [];
} else {
return explode(' ', $header_value);
}
};
// Assert cache miss + expected cache contexts + tags.
$this->drupalGet($absolute_url);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$actual_contexts = $get_cache_header_values('X-Drupal-Cache-Contexts');
$actual_tags = $get_cache_header_values('X-Drupal-Cache-Tags');
$this->assertIdentical($actual_contexts, $expected_contexts);
if ($actual_contexts !== $expected_contexts) {
debug('Missing cache contexts: ' . implode(',', array_diff($actual_contexts, $expected_contexts)));
debug('Unwanted cache contexts: ' . implode(',', array_diff($expected_contexts, $actual_contexts)));
}
$this->assertIdentical($actual_tags, $expected_tags);
if ($actual_tags !== $expected_tags) {
debug('Missing cache tags: ' . implode(',', array_diff($actual_tags, $expected_tags)));
debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $actual_tags)));
}
// Assert cache hit + expected cache contexts + tags.
$this->drupalGet($absolute_url);
$actual_contexts = $get_cache_header_values('X-Drupal-Cache-Contexts');
$actual_tags = $get_cache_header_values('X-Drupal-Cache-Tags');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$this->assertIdentical($actual_contexts, $expected_contexts);
if ($actual_contexts !== $expected_contexts) {
debug('Missing cache contexts: ' . implode(',', array_diff($actual_contexts, $expected_contexts)));
debug('Unwanted cache contexts: ' . implode(',', array_diff($expected_contexts, $actual_contexts)));
}
$this->assertIdentical($actual_tags, $expected_tags);
if ($actual_tags !== $expected_tags) {
debug('Missing cache tags: ' . implode(',', array_diff($actual_tags, $expected_tags)));
debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $actual_tags)));
}
// Assert page cache item + expected cache tags.
$cid_parts = array($url->setAbsolute()->toString(), 'html');
$cid = implode(':', $cid_parts);
$cache_entry = \Drupal::cache('render')->get($cid);
sort($cache_entry->tags);
$this->assertEqual($cache_entry->tags, $expected_tags);
if ($cache_entry->tags !== $expected_tags) {
debug('Missing cache tags: ' . implode(',', array_diff($cache_entry->tags, $expected_tags)));
debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $cache_entry->tags)));
}
}
示例11: testEntityCreation
/**
* Tests that when creating a feed item, the feed tag is invalidated.
*/
public function testEntityCreation()
{
// Create a cache entry that is tagged with a feed cache tag.
\Drupal::cache('render')->set('foo', 'bar', \Drupal\Core\Cache\CacheBackendInterface::CACHE_PERMANENT, $this->entity->getCacheTag());
// Verify a cache hit.
$this->verifyRenderCache('foo', array('aggregator_feed:1'));
// Now create a feed item in that feed.
Item::create(array('fid' => $this->entity->getFeedId(), 'title' => t('Llama 2'), 'path' => 'https://groups.drupal.org/'))->save();
// Verify a cache miss.
$this->assertFalse(\Drupal::cache('render')->get('foo'), 'Creating a new feed item invalidates the cache tag of the feed.');
}
示例12: cloudflare_ip_ranges
/**
* Get a list of cloudflare IP Ranges
*/
function cloudflare_ip_ranges()
{
if ($cache = \Drupal::cache()->get('cloudflare_ip_ranges')) {
return $cache->data;
} else {
$ip_blocks = file_get_contents(CLOUDFLARE_URL_IPV4_RANGE);
$cloudflare_ips = explode("\n", $ip_blocks);
$cloudflare_ips = array_map('trim', $cloudflare_ips);
\Drupal::cache()->set('cloudflare_ip_ranges', $cloudflare_ips, Cache::PERMANENT);
return $cloudflare_ips;
}
}
示例13: testEntityCreation
/**
* Tests that when creating a shortcut, the shortcut set tag is invalidated.
*/
public function testEntityCreation()
{
// Create a cache entry that is tagged with a shortcut set cache tag.
$cache_tags = ['config:shortcut.set.default'];
\Drupal::cache('render')->set('foo', 'bar', CacheBackendInterface::CACHE_PERMANENT, $cache_tags);
// Verify a cache hit.
$this->verifyRenderCache('foo', $cache_tags);
// Now create a shortcut entity in that shortcut set.
$this->createEntity();
// Verify a cache miss.
$this->assertFalse(\Drupal::cache('render')->get('foo'), 'Creating a new shortcut invalidates the cache tag of the shortcut set.');
}
示例14: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
$config = $this->config('medium.settings');
// Invalidate library cache if devmode has changed.
$devmode = $form_state->getValue('devmode');
if ($config->get('devmode') != $devmode) {
\Drupal::cache('discovery')->invalidate('library_info');
}
// Save config
$config->set('devmode', $devmode)->save();
parent::submitForm($form, $form_state);
}
示例15: formElement
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
{
/* @var $item LanguageItem */
$item = $items[$delta];
$value = $item->value;
// Add Languages to custom values: $this->options and $element[]
$this->options = $languages = $item->getSettableOptions();
// Cache available languages for this field for a day.
$field_name = $this->fieldDefinition->id();
\Drupal::cache('data')->set('languagefield:languages:' . $field_name, $languages, strtotime('+1 day', time()));
$element['value'] = $element + array('#type' => 'textfield', '#default_value' => !empty($value) && isset($languages[$value]) ? $languages[$value] : '', '#languagefield_options' => $languages, '#autocomplete_route_name' => $this->getSetting('autocomplete_route_name'), '#autocomplete_route_parameters' => array('field_name' => $field_name), '#size' => $this->getSetting('size'), '#placeholder' => $this->getSetting('placeholder'), '#maxlength' => 255, '#element_validate' => array(array(get_class($this), 'validateElement')));
return $element;
}