With constants coming from the framework you are using. i.e, ABSPATH
in WordPress.
How badly will it break the Dependency Injection principle if I do not add the value of that constant as a dependency in constructor
function of the class, and just use it directly inside method?
Say, strictly DI speaking, you need to do something like:
class Foo {
private $abspath;
public function __construct(string $abspath) {
$this->abspath = $abspath
}
public function get_assets_dir() {
return $this->abspath . '/assets/';
}
}
$foo = new Foo(ABSPATH);
$foo->get_assets_dir();
but instead something like?
class Foo {
public function __construct() {
//nothing here.
}
public function get_assets_dir() {
return ABSPATH . '/assets/';
}
}
Do I really still have to do it if it will always be defined since it sits on top of a framework that defines it by default?
Strictly speaking, yes. (Although it's called the "Dependency Inversion Principle", not "Dependency Injection" principle. The "Dependency Injection Pattern" it's a subpattern of the "Inversion of Control" principle; related but not the same. Read more about this here.
ABSPATH
is dependency for your Foo
class, it is defined outside by different part of the application. If your class needs that value, and aims to be completely decoupled from the "framework", you should inject it (disregarding that the constant belongs to the global state, if you are really encapsulating your class, it doesn't need to be aware of that).
Realistically, if your class is solely for use in Wordpress (and it looks that way), I wouldn't worry too much. You are already coupled to your "framework" anyway.