Skip to content

RFC: Autowiring scalar parameters #40327

Closed
@maldoinc

Description

@maldoinc

Hi all,

In a large symfony codebase we are in the process of upgrading it from 3.4 to 4, one of the tasks is to remove the manual service declarations (we used xml) and fetching them from the container in favor of autowiring. During this process, DI works for services but we still need to declare into a yaml file the values for scalar arguments. Yet again having some part of the service declaration in a separate file.

Description

What I would like to propose is the addition of a new mechanism (attribute/annotation), which would bind parameters to the arguments removing the need to declare a part of the service in a separate file (I am aware of the possibility of binding specific argument names to a parameter, but personally I am not a fan of said functionality due to having to memorize what argument name belongs to what parameter).

The advantages of this approach would be that the service can be fully self contained, with its entire declaration in the constructor. Below are two examples using a php attribute and an annotation. The names used for the attribute/annotation are just an example, what I'm looking forward to hearing from is about the idea in general.

If this looks like a positive change, I can contribute the necessary patch to implement it.

Looking forward to your thoughts

Example

// Example using php8 attribute to bind the kernel.debug parameter to the $isDebug argument
class DummyService
{
    public function __construct(
        TranslatorInterface $translator,
        LoggerInterface $logger,

        #[Parameter("kernel.debug")] 
        bool $isDebug
    )
    {
    }
}


// Similar to the above example but instead an annotation is used.
class DummyService
{
    /**
     * @BindParameter("kernel.debug", to="$isDebug")
     */
    public function __construct(TranslatorInterface $translator, LoggerInterface $logger, bool $isDebug)
    {
    }
}```

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions