Silverstripe 在 Injector 中查找 class 以便 class 可以被依赖注入覆盖

Silverstripe look up the class in the Injector so that the class can be overriden by dependency injection

根据 Silverstripe 文档:

Using the create() method provides chainability, which can add elegance and brevity to your code, e.g. Player::create()->write(). More importantly, however, it will look up the class in the Injector so that the class can be overriden by dependency injection.

有人可以解释一下 "it will look up the class in the Injector so that the class can be overridden by dependency injection" 部分吗?

我想你可能指的是这个:

Injector:
  MyClass1:
    class: MyClass2

上面的 YML 配置片段将告诉 Injector(几乎所有 SS 的对象都通过它实例化)在调用 MyClass1::create() 时使用 MyClass2 而不是 MyClass1

当您的 Player Class 依赖于 AnotherClass 时,最好将 AnotherClass 的实例传递给 Player。您可以在此处阅读更多相关信息:What is dependency injection?

SilverStripe 有一个内置的依赖注入解决方案:注入器 Class。参见 https://docs.silverstripe.org/en/3.3/developer_guides/extending/injector/

因此,当您调用 Player::create(); 时,SilverStripe 将查找要使用的正确 Class(默认为 Player Class,但可以用配置文件覆盖),创建一个新实例它,注入它的依赖关系和 return 给你。

如果您是 SilverStripe 的新手,您可能会忽略所有这些。