Skip to content

Instantly share code, notes, and snippets.

@phalcon
Last active December 11, 2015 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phalcon/4544542 to your computer and use it in GitHub Desktop.
Save phalcon/4544542 to your computer and use it in GitHub Desktop.
<?php
class NewsController extends \Phalcon\Mvc\Controller
{
public function indexAction()
{
}
/**
* @Cache(lifetime=86400)
*/
public function showAction($slug)
{
$this->view->article = Article::findFirstByTitle($slug);
}
}
<?php
class CacheEnablerPlugin extends \Phalcon\Mvc\User\Plugin
{
public function beforeExecuteRoute($event, $dispatcher)
{
$annotations = $this->annotations->getMethod(
$dispatcher->getActiveController(),
$dispatcher->getActiveMethod()
);
//Check if the method has an annotation 'Cache'
if ($annotations->has('Cache')) {
//Get the lifetime
$lifetime = $annotations->get('Cache')->getNamedParameter('lifetime');
//Enable the cache
$this->view->cache(array('lifetime' => $lifetime));
}
}
}
<?php
$di = new \Phalcon\DI\FactoryDefault();
$eventsManager = new \Phalcon\Events\Manager();
//Attach the plugin to 'dispatch' events
$eventsManager->attach('dispatch', new CacheEnablerPlugin());
$di['dispatcher'] = function() use ($eventsManager) {
$dispatcher = new \Phalcon\Mvc\Dispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
};
$di['view'] = function() {
$view = new \Phalcon\Mvc\View();
$view->setViewsDir('unit-tests/views/');
return $view;
};
$di['annotations'] = function() {
return new \Phalcon\Annotations\Adapter\Memory();
};
$di['viewCache'] = function() {
//Cache data for one day by default
$frontCache = new \Phalcon\Cache\Frontend\Output(array(
"lifetime" => 86400
));
//Memcached connection settings
$cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array(
"host" => "localhost",
"port" => "11211"
));
return $cache;
};
$app = new \Phalcon\Mvc\Application();
$app->setDi($di);
echo $app->handle()->getContent();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment