Created
November 6, 2015 11:38
-
-
Save DuaelFr/5c07c8911ac0d1f1f752 to your computer and use it in GitHub Desktop.
Redirect to the last changed node of a type with elegant cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* Contains \Drupal\faf_videos\Controller. | |
*/ | |
namespace Drupal\faf_videos; | |
use Drupal\Core\Cache\Cache; | |
use Drupal\Core\Cache\CacheBackendInterface; | |
use Drupal\Core\Controller\ControllerBase; | |
use Drupal\Core\Entity\Query\QueryFactory; | |
class Controller extends ControllerBase { | |
/** | |
* The entity query factory. | |
* | |
* @var \Drupal\Core\Entity\Query\QueryFactory | |
*/ | |
protected $queryFactory; | |
/** | |
* The cache backend. | |
* | |
* @var \Drupal\Core\Cache\CacheBackendInterface | |
*/ | |
protected $cache; | |
/** | |
* Constructs a \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators object. | |
* | |
* @param \Drupal\Core\Entity\Query\QueryFactory $query_factory | |
* The entity query factory. | |
*/ | |
public function __construct(QueryFactory $query_factory, CacheBackendInterface $cache) { | |
$this->queryFactory = $query_factory; | |
$this->cache = $cache; | |
} | |
/** | |
* /videos controller endpoint. Redirects to the last changed video. | |
*/ | |
public function last() { | |
$cid = 'faf_video:last'; | |
// Retrieve value from cache if it's in. | |
if ($cache = $this->cache->get($cid)) { | |
$nid = $cache->data; | |
} | |
// Find the last changed video nid as it's not in cache. | |
else { | |
$query = $this->queryFactory->get('node'); | |
$last_video = $query->condition('type', 'video') | |
->sort('changed', 'DESC') | |
->range(0, 1) | |
->execute(); | |
$nid = key($last_video); | |
// Save the value in cache using the node_list tag to auto invalidate | |
// when a node is saved. | |
$this->cache->set($cid, $nid, Cache::PERMANENT, ['node_list']); | |
} | |
// If no video is found, return 404. | |
if (empty($nid)) { | |
throw new NotFoundHttpException(); | |
} | |
// Redirect to the found video. | |
return $this->redirect('entity.node.canonical', ['node' => $nid]); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
faf_videos.controller: | |
class: Drupal\faf_videos\Controller | |
arguments: ['@entity.query', '@cache.default'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment