martin-hughes / auryn

IoC Dependency Injector
MIT License
6 stars 1 forks source link

Nullable param should be `null` by default #2

Open mskocik opened 2 years ago

mskocik commented 2 years ago

Proposed solution was working with original auryn on php7.4. However it behaves differently in php8.1. What do you think about changing this default behavior to this?

class HardDep {}
class NullableDep {}

class ToCreate
{
  public function __construct(
    private HardDep $required = null,
    private ?NullableDep $optional = null
  ) {}
}

$auryn = new Injector();
$obj = $auryn->make(ToCreate::class);
$obj->required instanceof HardDep;     // true
$obj->optional instanceof NullableDep; // false - previously it creates NullableDep instance
$obj->optional === null                // true

When you think about this, it the correct behaviour based on __constructor signature. If $optional is nullable, you need to use auryn's method to prepare (using share, delegates or alias methods).

This is required especially in case when there are nested dependencies with typeless constructor params. Auryn would throw an exception in that case.

I know it would break default behaviour and point 5. defined on doc section Dependency Resolution, but it's impossible to have both "modes" working at the same time. If you are willing to accept this change, I can hapilly create PR for this.

martin-hughes commented 2 years ago

My apologies, evidently I haven't got my Github notifications setup properly - only just seen this!

The current behaviour is a bit weird, but it is what the specifications (such as they are) call for. I know the project I was working on relied on $optional being created.

I don't really want to change the specification outside of a major release, if I ever make one. With that in mind, for the time being I won't merge your change if you make a PR. If I look like making a major release, please remind me then :)

mskocik commented 2 years ago

I completely understrand. It really questionable, what is expected behavior, which changes between php versions :)

And because it was big breaking change for one of my projects, I've implemented it myself. Just wanted to raise this issue.