yiisoft/di

New in initializers in PHP 8.1

mj4444ru opened this issue · 7 comments

class Color {}

class Blue extends Color {}

class Car
{
    public function __construct(public readonly Color $color = new Blue())
    {
    }
}

$config = ContainerConfig::create()->withDefinitions([]);
$container = new Container($config);

I am expecting the next 2 lines of code to return the result.

var_dump(new Car());
var_dump($container->get(Car::class));

But I get a different result.

object(App\Controller\Car)
  public readonly App\Controller\Color 'color' => object(App\Controller\Blue)
object(App\Controller\Car)
  public readonly App\Controller\Color 'color' => object(App\Controller\Color)

It seems to me that the result in this case should be the same.
An exception can only be an explicitly defined definition for an expected class.

Q A
Version 1.0.0
PHP version 8.1

For

public function __construct(LoggerInterface $logger = new NullLogger())

you expect NullLogger instead of configured LoggerInterface instance?

@BoShurik his case is when there's no LoggerInterface configured in the container. In this case falling back to NullLogger seems to be correct action.

From the container POV LoggerInterface and Color - just a service ids, but Color is instantiable so can be fetched from container without definition.
What about public function __construct(public readonly ?Color $color = null))? Should container create Color instance?

Default should be used in this case which is null.

If we want to use something instead of the default, we have to customize the container.
I believe that the default takes precedence over the value of the same type in the container itself.
At the same time, it is naturally the highest priority for determining the configuration of the container.

The same goes for factory behavior.
yiisoft/factory#157

vjik commented

If we want to use something instead of the default, we have to customize the container. I believe that the default takes precedence over the value of the same type in the container itself. At the same time, it is naturally the highest priority for determining the configuration of the container.

Container resolve dependencies and if container can resolve dependency, he does it, and if he doesn't, then used default value. So object is from the container has priority over default value. I think this is correct.

Added support objects as default values here: yiisoft/definitions#31