nortmas
9/27/2017 - 2:47 PM

Lazy builder

//When should I use a lazy builder?

//Content that would have a high cardinality if cached. For example, a block that displays the user's name. It can be cached, but because it varies by user, it's also likely to result in cached objects with a low hit rate
//Content that cannot be cached or has a very high invalidation rate. For example, displaying the current date/time, or statistics that need to be as up-to-date as possible at all times
//Content that requires a lengthy and potentially slow assembly process. For example, a block displaying content from a third-party API where requesting content from the API incurs overhead


$build['lazy'] = [
  '#lazy_builder' => [
    // Function or method to call.
    $this::class . '::lazyDateFormat',
    ['Y-m-d']
  ]
];

// Callback formats

//Call a defined function
$build['item']['#lazy_builder'] = ['render_example_lazy_buider', ['argument1', 'argument2']];

//Call the build() method on $this class:
$build['item']['#lazy_builder'] = [static::class . '::build', ['argument1', 'argument2']];

//Call the build() method on any class
use Drupal\render_example\LazyBuilder;
$build['item']['#lazy_builder'] = [LazyBuilder::class . '::build', ['argument1', 'argument2']];

//Call a service. Use this whenever you need to inject additional dependencies into the class performing the lazy building operation. You'll need to first declare a new service, and then reference the service by its name.
$build['item']['#lazy_builder'] = ['service.name:method', ['argument1', 'argument2']];