
The Block Plugin Class
public function build(): array {
$uri = $this->handler->getRandomFile();
```
if (!$uri) {
return [
'#markup' => '<p>No unmanaged files found.</p>',
];
}
return [
'#theme' => 'image',
'#uri' => $uri,
'#alt' => $this->t('Random unmanaged file'),
'#cache' => [
'max-age' => 1,
],
];
```
}
Enable and Place the Block
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private FileHandler $handler,
private FileUrlGeneratorInterface $urlGen,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
The Factory Method
namespace Drupalunmanaged_filesPluginBlock;
use DrupalCoreBlockBlockBase;
use DrupalCoreFileFileUrlGeneratorInterface;
use Drupalunmanaged_filesServiceFileHandler;
use SymfonyComponentDependencyInjectionContainerInterface;
use DrupalCorePluginContainerFactoryPluginInterface;
final class UnmanagedFilesBlock extends BlockBase implements ContainerFactoryPluginInterface {
The Constructor
The class extends BlockBase
and implements ContainerFactoryPluginInterface
, which lets us inject our file handler and URL generator services from Drupal’s service container.
public static function create(ContainerInterface $c, array $configuration, $plugin_id, $plugin_definition): self {
$handler = $c->get('unmanaged_files.handler');
```
$urlGen = $c->get('file_url_generator');
return new self(
$configuration,
$plugin_id,
$plugin_definition,
$handler,
$urlGen,
);
```
}
The Build Method
The build()
method is what Drupal calls to render the block. It asks the file handler for a random unmanaged file. If a file is found, it returns a render array using the image
theme. If no file is found, it returns a simple message. The max-age
cache metadata is set to 1 second so that refreshing the page quickly rotates images.