Dependency Retriever
Categories
Component ID
Component name
Component type
Maintenance status
Development status
Component security advisory coverage
Downloads
Component created
Component changed
Component body
This module provides an alternative class factory and dependency injection method based on bartfeenstra/dependency-retriever.
The retriever.factory service
(BartFeenstraDependencyRetrieverFactoryFactory) can instantiate any class, provided that its dependencies (constructor arguments) have default values, overridden values at instantiation time, or suggested dependencies.
Dependency suggestions
Dependencies can be suggested through @suggestedDependency annotations as in the following example:
class ClassWithSuggestedDependencies
{
/**
* Constructs a new instance.
*
* @suggestedDependency drupalContainerParameter:filter_protocols $filter_protocols
* @suggestedDependency drupalContainerService:entity_type.manager $entity_type_manager
* @suggestedDependency drupalEntityTypeHandler:user.access $user_access_control_handler
* @suggestedDependency drupalEntityTypeHandler:node.form.delete $node_delete_form
*
* @param string[] $filter_protocols
* @param DrupalCoreEntityEntityTypeManagerInterface $entity_type_manager
* @param DrupaluserUserAccessControlHandler $user_access_control_handler
* @param Drupal
odeFormNodeDeleteForm $node_delete_form
*/
public function __construct(array $filter_protocols, EntityTypeManagerInterface $entity_type_manager, UserAccessControlHandler $user_access_control_handler, NodeDeleteForm $node_delete_form)
{
}
}
This module provides the following dependency retrievers:
drupalContainerParameterto retrieve container parameters. Dependency IDs are parameter names.drupalContainerServiceto retrieve container services. Dependency IDs are service IDs.drupalEntityTypeHandlerto retrieve entity type handlers. Dependency IDs are entity type IDs, handler types, and handler operations (optional) concatenated by periods, such asnode.form.editoruser.access.
Why?
Drupal core provides several interfaces with factory methods. While these do a fairly good job at dependency injection, they prevent classes from being used outside of Drupal, and make these classes control their own dependency injection. If classes require dependencies that are not specified by the factory methods, they need to locate these themselves (breaching isolation), or have them passed on through undocumented arrays in the factory method.
This module solves these issues by:
- decoupling classes from the framework/application they are used in
- using constructors for class instantiation directly, allowing classes to specify exactly which requirements they have
- allowing classes to suggest which framework-specific dependencies they should receive, lowering the burden on these frameworks
- leaving the framework and calling code with final say over which dependencies are injected
