createObject allows app-wide object configuration
BaseYii::createObject() uses BaseYii::$objectConfig to configure your objects. This means that if you want to change an object’s configuration at runtime throughout your entire app, you can modify BaseYii::$objectConfig without having to modify the class itself or any instances where it’s constructed.
You don’t get that flexibility with new. It reminds me a bit of the widget factory in Yii1. (Probably still in Yii2? Haven’t checked yet.)
Clarification: Swapping classes at runtime
Here’s what I was getting at:
$foo = Yii::createObject('@someAlias'); // is a Foo
$bar = Yii::createObject('@someAlias'); // is a Bar
The name of the alias stays the same, but the returned object is different. But honestly after some thought I’m not sure it’s necessary:
I get it’s just an example, but is this a common pattern for injecting dependencies in Yii? (Dependency configurations as class properties.)
I’m used to explicitly declaring dependencies in constructors and/or setters:
public function __construct(EngineInterface $engine)
$this->engine = $engine;
public function fly()
I’ve always wondered how to Yii-ify it, or make it more Yii-like in general. You don’t really see code like this in the docs. (I think? Maybe I’m just forgetting examples.)
You have to explicitly specify the namespace when using the class map, so it’s not quite the same as aliasing.