With the release of Drupal 11.3, the new DrupalInstalled class has been introduced for site builders and developers, simplifying cache management and container rebuilds.
What’s New
The Drupal Scaffold Composer plugin now generates a file:
vendor/drupal/DrupalInstalled.php Inside it, there’s a constant:
\Drupal\DrupalInstalled::VERSIONS_HASH This constant contains a hash of all installed Composer package versions, including:
Drupal core
Contrib modules
Third-party PHP packages
The root project itself
The hash is updated automatically whenever you run composer install or composer update.
Why It Matters
Previously, if you updated a contrib module or added a new service, you often needed to create empty post-update hooks just to rebuild the container and load new services. With DrupalInstalled, this step is no longer required — the container automatically detects when code changes.
How to Use DrupalInstalled in Your Custom Module
Suppose you want to create a cache in your custom module that should automatically invalidate whenever any package is updated. Instead of using a fixed cache key, use VERSIONS_HASH:
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\DrupalInstalled;
class ExampleService {
protected CacheBackendInterface $cache;
public function __construct(CacheBackendInterface $cache) {
$this->cache = $cache;
}
public function getExpensiveData(): array {
$cid = 'example_data:' . DrupalInstalled::VERSIONS_HASH;
if ($cache = $this->cache->get($cid)) {
return $cache->data;
}
// Example of an expensive operation
$data = $this->generateData();
$this->cache->set($cid, $data, CacheBackendInterface::CACHE_PERMANENT);
return $data;
}
protected function generateData(): array {
// Any logic that generates data
return ['time' => time(), 'info' => 'some expensive data'];
}
}
How It Works
The cache key includes a hash of all packages.
When you update any module or package via Composer, the hash changes → the old cache automatically becomes invalid.
This ensures that your data is always up-to-date after updates without manual intervention.
Composer Scaffold Plugin Note
The drupal/core-composer-scaffold plugin is now a required dependency of Drupal core. If you previously disabled it, add this to your composer.json:
"scripts": {
"pre-autoload-dump": "Drupal\\Composer\\Plugin\\Scaffold\\Plugin::preAutoloadDump"
} This ensures the \Drupal\DrupalInstalled class is correctly generated during autoload dumping.
Who Benefits
Module developers: easier handling of services and cache.
Site builders and administrators: smoother updates and fewer container issues.
Distribution developers: container rebuilds correctly when installing any package.
Conclusion
DrupalInstalled::VERSIONS_HASH provides a simple and reliable way to tie cache and other mechanisms to the current state of installed packages. It reduces the need for “magic” update hooks and makes Drupal’s container behavior more predictable and robust.
Comments