Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support autowiring non-object parameters with attributes #29

Open
Firehed opened this issue Dec 1, 2021 · 0 comments
Open

Support autowiring non-object parameters with attributes #29

Firehed opened this issue Dec 1, 2021 · 0 comments
Labels
enhancement New feature or request

Comments

@Firehed
Copy link
Owner

Firehed commented Dec 1, 2021

Currently, it's not possible to use autowiring on a class with:

  • untyped constructor parameters
  • typed constructor parameters where the type isn't configured (implicitly, any scalar)

Thanks to Attribute support in PHP 8, I think it should be possible to define and support attributes that enable this. An example of how this may look:

// -- attribute definition --
#[Attribute(Attribute::TARGET_PARAMETER)]
class Value
{
  public function __construct(public string $name) {}
}

// -- class definition file --

use Firehed\Container\Value;

class MyClass
{
  public function __construct(
    #[Value('my_array')]
    array $params,
  ) { ... }
}

// -- config definition file --

return [
  MyClass::class,

  'my_array' => [
    'foo' => 'bar',
  ],
];

This should also work in (relatively rare) situations where a class needs a non-standard definition is needed:

class MySpecialConnection
{
  public function __construct(#[Value('otherPDO')] PDO $pdo) { ... }
}
// defs
return [
  PDO::class => function ($c) {
    // ...
  },
  'otherPDO' => function ($c): PDO {
    // ...
  },
  // BEFORE: cannot autowire, or the first PDO definition will be used
  MySpecialConnection::class => function ($c) {
    return new MySpecialConnection($c->get('otherPDO'));
  },
  // AFTER: correct value is configured by the parameter attribute
  MySpecialConnection::class,
];

Looking at the config definitions in a relatively large project, the majority of those with non-autowired definitions via closures are to provide specific values from the container without additional logic required.

@Firehed Firehed added the enhancement New feature or request label Dec 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant