AbstractServiceProvider::add_with_auto_arguments()protectedWC 1.0

Register a class in the container and use reflection to guess the injection method arguments.

WARNING: this method uses reflection, so please have performance in mind when using it.

Method of the class: AbstractServiceProvider{}

No Hooks.


DefinitionInterface. The generated container definition.


// protected - for code of main (parent) or child class
$result = $this->add_with_auto_arguments( $class_name, $concrete, $shared ) : DefinitionInterface;
$class_name(string) (required)
Class name to register.
The concrete to register. Can be a shared instance, a factory callback, or a class name.
Default: null
Whether to register the class as shared (get always returns the same instance) or not.
Default: false

AbstractServiceProvider::add_with_auto_arguments() code WC 8.7.0

protected function add_with_auto_arguments( string $class_name, $concrete = null, bool $shared = false ) : DefinitionInterface {
	$definition = new Definition( $class_name, $concrete );

	$function = $this->reflect_class_or_callable( $class_name, $concrete );

	if ( ! is_null( $function ) ) {
		$arguments = $function->getParameters();
		foreach ( $arguments as $argument ) {
			if ( $argument->isDefaultValueAvailable() ) {
				$default_value = $argument->getDefaultValue();
				$definition->addArgument( new RawArgument( $default_value ) );
			} else {
				$argument_class = $this->get_class( $argument );
				if ( is_null( $argument_class ) ) {
					throw new ContainerException( "Argument '{$argument->getName()}' of class '$class_name' doesn't have a type hint or has one that doesn't specify a class." );

				$definition->addArgument( $argument_class->name );

	// Register the definition only after being sure that no exception will be thrown.
	$this->getContainer()->add( $definition->getAlias(), $definition, $shared );

	return $definition;