Skip to content
This repository has been archived by the owner on Jul 16, 2021. It is now read-only.

Set property to a config value via an Attribute #2662

Open
KKSzymanowski opened this issue Jul 8, 2021 · 1 comment
Open

Set property to a config value via an Attribute #2662

KKSzymanowski opened this issue Jul 8, 2021 · 1 comment

Comments

@KKSzymanowski
Copy link

KKSzymanowski commented Jul 8, 2021

Ability to set a property of an object to some config value when the object is constructed by the Container.
API would look something like this:

class FooController extends Controller
{
    #[Config('app.url')]
    protected $appUrl;

    #[Config('foo.bar', 'some default value')]
    protected $fooBar;
}

Proof of concept:

  1. Create a Config attribute:
#[Attribute(Attribute::TARGET_PROPERTY)]
class Config {
    public function __construct($key, $default = null)
    {

    }
}
  1. Change the last line in Illuminate\Container\Container::build()
- return $reflector->newInstanceArgs($instances);
+ $object = $reflector->newInstanceArgs($instances);
+ 
+ foreach($reflector->getProperties() as $property) {
+     foreach($property->getAttributes() as $attribute) {
+         if($attribute->getName() == Config::class) {
+             $property->setAccessible(true);
+             $property->setValue($object, call_user_func_array('config', $attribute->getArguments()));
+         }
+     }
+ }
+ 
+ return $object;
  1. Use the Attribute in a controller and see that the property value has been set to a value from app configuration.

What do you think?

@KKSzymanowski
Copy link
Author

@taylorotwell Can I get your opinion about this?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant