Last active
May 7, 2026 14:21
-
-
Save aklump/9a790adc80d06975a85e0dacca4b6165 to your computer and use it in GitHub Desktop.
Provides access to the typed entity repository manager in Drupal custom classes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| use Drupal\typed_entity\RepositoryManager; | |
| /** | |
| * Provides access to the typed entity repository manager. | |
| * | |
| * Prefer dependency injection when the consuming class supports it: | |
| * | |
| * @code | |
| * use Drupal\typed_entity\RepositoryManager; | |
| * | |
| * final class ExampleService { | |
| * use HasTypedEntitiesTrait; | |
| * | |
| * public function __construct( | |
| * protected RepositoryManager $typedEntityRepositoryManager, | |
| * ) {} | |
| * | |
| * public function doSomething(): void { | |
| * $repository_manager = $this->typedEntityRepositoryManager(); | |
| * } | |
| * } | |
| * @endcode | |
| * | |
| * In classes that cannot easily use constructor injection, such as some Drupal | |
| * hooks, legacy classes, plugin edge cases, or objects not created by the | |
| * service container, this trait lazily falls back to Drupal's global service | |
| * container: | |
| * | |
| * @code | |
| * final class LegacyExample { | |
| * use HasTypedEntitiesTrait; | |
| * | |
| * public function doSomething(): void { | |
| * // Falls back to \Drupal::service('typed_entity.repository_manager') | |
| * // when $this->typedEntityRepositoryManager has not been injected. | |
| * $repository_manager = $this->typedEntityRepositoryManager(); | |
| * } | |
| * } | |
| * @endcode | |
| * | |
| * This gives consumers a consistent method to call while still allowing the | |
| * best available integration style: | |
| * - injected service when available; | |
| * - global container fallback when injection is not practical. | |
| * | |
| * Classes using this trait may define a `$typedEntityRepositoryManager` | |
| * property themselves, typically via constructor property promotion, to make | |
| * the dependency explicit and testable. | |
| */ | |
| trait HasTypedEntitiesTrait { | |
| public function typedEntityRepositoryManager(): RepositoryManager { | |
| if (!isset($this->typedEntityRepositoryManager)) { | |
| $this->typedEntityRepositoryManager = \Drupal::service('typed_entity.repository_manager'); | |
| } | |
| return $this->typedEntityRepositoryManager; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment