. namespace core\hook; use DI\ContainerBuilder; use core\attribute\label; /** * Allow for init-time configuration of the Dependency Injection container. * * @package core * @copyright 2023 Andrew Lyons * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ #[label('A hook to allow per-component configuration of the DI container.')] class di_configuration { /** * Create the Dependency Injection configuration hook instance. * * @param ContainerBuilder $builder */ public function __construct( /** @var ContainerBuilder The PHP-DI Builder */ protected ContainerBuilder $builder, ) { } /** * Add a definition to the Dependency Injection container. * * A definition is a callable that returns an instance of the service. * * The callable can take arguments which are resolved using the DI container, for example a definition for the * following example service requires \moodle_database, and \core\formatting which will be resolved using the DI * container. * * * $hook->add_definition( * id: \mod\example\service::class, * definition: function ( * \moodle_database $db, * \core\formatting $formatter, * ): \mod\example\service { * return new \mod\example\service( * $database, * $formatter, * $some, * $other, * $args, * )' * }, * ); * * * @param string $id The identifier of the container entry * @param callable $definition The definition of the container entry * @return self * @example */ public function add_definition( string $id, callable $definition, ): self { $this->builder->addDefinitions([ $id => $definition, ]); return $this; } }