Constants on di container in PHP

Viewed 87

I see a practice used in several frameworks in recent times. It consists of registering the objects in the container with the class constant instead of a string. Usually the objects are added following example below.

$container[MyClass::name] = function(){
    // create object here
}

I usually use a string:

$container['MyClass'] = function(){
    // create object here
}

I would like to know the facilities of this practice.

1 Answers

This has to do with how IDE's do refactoring.

Let's say you have the class MyClass

And you use:

$container['MyClass'] = function(){
    // create object here
}

If you rename the class 'MyClass', you'll need to rename the string everywhere you use this. Refactoring tools will have a harder time to figure out that the string 'MyClass', in this case is a reference to a class, rather than a piece of random proze.

If you use:

$container[MyClass::name] = function(){
   // create object here
}

You'll need to rename the class MyClass, but many IDE's (e.g. phpstorm, vscode, etc.) have tools to automatically rename (refactor) the reference to the class everywhere in your code, and since you used a class and not a string they'll figure out that MyClass will need to be renamed.

This way it's a lot easier to maintain the second than the first.

Related