This is an example of how to use Value Objects for dependency injection, as a response to a blog post by Tom McFarlin:
Last active
September 29, 2017 17:15
-
-
Save schlessera/7417209b376419492fdf7290c7b3a022 to your computer and use it in GitHub Desktop.
Using Value Objects for Dependency Injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$plugin = new Plugin( new PluginRoot( __FILE__ ) ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Plugin | |
{ | |
protected $plugin_root; | |
private $loaded; | |
public function __construct(PluginRoot $plugin_root) | |
{ | |
$this->loaded = false; | |
$this->plugin_root = $plugin_root; | |
} | |
public function isLoaded() | |
{ | |
return $this->loaded; | |
} | |
public function load() | |
{ | |
// ... | |
} | |
public function getSubscribers() | |
{ | |
return [ | |
new OtherPluginClass($this->plugin_root) | |
]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class PluginRoot { | |
protected $file; | |
public function __construct( $file ) { | |
$this->file = $file; | |
} | |
public function get_path() { | |
return plugin_dir_path( $this->file ); | |
} | |
public function get_url() { | |
return plugin_dir_url( $this->file ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment