0

According to the Silverstripe documentation:

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.

Can somebody explain the "it will look up the class in the Injector so that the class can be overridden by dependency injection" part?

scrowler
  • 24,273
  • 9
  • 60
  • 92
The Man
  • 385
  • 1
  • 3
  • 12

2 Answers2

4

I think you may be referring to this:

Injector:
  MyClass1:
    class: MyClass2

The above YML config snippet will tell Injector (Via which almost all SS' objects are instantiated) to use MyClass2 instead of MyClass1 when MyClass1::create() is called.

theruss
  • 1,690
  • 1
  • 12
  • 18
  • Does this apply to all classes that are instantiated via `MyClass1::create()`, but not for classes created via `new MyClass1` as much of the framework code still does? – scrowler May 31 '16 at 22:41
  • Correct. `new MyClass()` is plain old PHP. It'd be very hard to "hijack" this syntax, hence SS' coming up with `Injector's` `create()` method. FYI there's also `createWithArgs()` too which many people miss. – theruss May 31 '16 at 22:49
1

When your Player Class depends on AnotherClass it is good practice to pass an instance of AnotherClass to Player. You can read more about this here: What is dependency injection?

SilverStripe has a build in Solution for Dependecy Injection: The Injector Class. See https://docs.silverstripe.org/en/3.3/developer_guides/extending/injector/

So when you call Player::create(); SilverStripe will look up the correct Class to use (defaults to Player Class but can be overridden with config files), create a new instance of it, inject its Dependencies and return that to you.

If you are new to SilverStripe you can probably ignore all that.

Community
  • 1
  • 1
jbe
  • 1,722
  • 1
  • 12
  • 20