For Drupal 7:
For Drupal 7
Drupal has the function drupal_page_is_cacheable() which can be used to set a page to uncacheable.
Here is the documentation: https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_page_is_cacheable/7
For Drupal 8:
For Drupal 8
// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();
Then the code is:
public function myPage() {
\Drupal::service('page_cache_kill_switch')->trigger();
return [
'#markup' => time(),
];
}
As usual, clean your cache once done.
Best practice (Drupal 8 | 9 | 10)
For performance and good practice reasons it is recommended to use dependency injection inside your Controller class.
modules/custom/my_module/MyController.php
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\PageCache\ResponsePolicy\KillSwitch;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* A controller class that respects Drupal coding standards.
*
* @see https://www.drupal.org/docs/develop/standards
*/
class MyController extends ControllerBase {
/**
* Page cache kill switch.
*
* @var \Drupal\Core\PageCache\ResponsePolicy\KillSwitch
*/
protected $killSwitch;
/**
* {@inheritdoc}
*/
public function __construct(KillSwitch $kill_switch) {
$this->killSwitch = $kill_switch;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('page_cache_kill_switch')
);
}
/**
* Render my page with a renderable array.
*
* @return array
*/
public function myPage() : array {
$this->killSwitch->trigger();
return [
'#markup' => time(),
];
}
}