The CacheableDependencyInterface provides the methods necessary to do some calculation (build a render array, calculate a number, anything) that is invalidated automatically whenever the objects that the calculation depends on is modified. Objects that implement CacheableDependencyInterface can communicate their cacheability in a standardized way, so that the calculation can be easily cached using the Drupal Cache API. This will commonly be used to fill out the #cache property of a render array.
One of the key advantages to using this interface, is that it allows an object to provide all the necessary details about how it should be turned into a cacheable render array, without requiring that class to have knowledge of complex patterns like #pre_render.
Before CacheableDependencyInterface:
class SomeClass {
protected function doBuild() {
// something expensive
}
public function build() {
return array(
'content' => array(
// SomeClass has intimate knowledge of render API semantics and has to
// put its expensive work in a #pre_render callback.
'#pre_render' => array(array($some_class, 'doBuild')),
),
'#cache' => array(
'keys' => array('some_class', $some_class->id()),
'tags' => array('content' => TRUE),
'expire' => REQUEST_TIME + $this->settings['max_age'],
),
);
}
}
class SomeClassViewBuilder {
public function viewMultiple() {
// View builder cannot get cache info without building the entire render
// array.
$build[$entity_id] = $some_class->build();
}
}
With CacheableDependencyInterface:
class SomeClass implements CacheableDependencyInterface {
public function build() {
// something expensive
}
public function getCacheTags() {
return array('content' => TRUE);
}
public function getCacheMaxAge() {
return $this->settings['max_age'];
}
}
class SomeClassViewBuilder {
public function viewMultiple() {
$build[$entity_id] += array(
'content' => array(
// View Builder can now move the expensive work to a #pre_render
// callback so that the cacheable object isn't responsible for getting
// this right.
'#pre_render' => array(array($some_class, 'build')),
),
'#cache' => array(
'keys' => ['some_class', $some_class->id()],
'tags' => $some_class->cacheTags(),
'expire' => REQUEST_TIME + $some_class->cacheMaxAge(),
),
);
}
}