Created
April 16, 2011 22:07
-
-
Save GodsBoss/923547 to your computer and use it in GitHub Desktop.
Verschiedene Implementierungen einer Client-Klasse mit einer optionalen Abhängigkeit.
This file contains hidden or 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 | |
/** | |
* Something the Client may depend on or not. | |
*/ | |
interface Dependency{ | |
public function action();} | |
/** | |
* The Client. | |
*/ | |
interface Client{ | |
public function doSomething();} | |
/** | |
* Implementation of the dependency which will do something. | |
*/ | |
class UsefulDependencyImplementation implements Dependency{ | |
public function action(){ | |
/* Do something. */}} | |
/** | |
* Client implementation using setter injection. The dependency may or may not | |
* be injected. | |
*/ | |
class ClientImplementationWithOptionalDependency implements Client{ | |
private $dep; | |
public function setDependency(Dependency $dep){ | |
$this->dep = $dep;} | |
public function doSomething(){ | |
/* Some client logic. */ | |
if (isset($this->dep)){ | |
$this->dep->action();} | |
/* Some client logic. */}} | |
/** | |
* Null implementation of the dependency. Does nothing. | |
*/ | |
class DependencyNullImplementation implements Dependency{ | |
public function action(){}} | |
/** | |
* Client implementation which needs always an object satisfying the | |
* Dependency's interface. | |
*/ | |
class ClientImplementationWithMandatoryDependency implements Client{ | |
private $dep; | |
public function __construct(Dependency $dep){ | |
$this->dep = $dep;} | |
public function doSomething(){ | |
/* Some client logic. */ | |
$this->dep->action(); | |
/* Some client logic. */}} | |
// Create client using the dependency. | |
$client = new ClientImplementationWithOptionalDependency(); | |
$client->setDependency(new UsefulDependencyImplementation()); | |
// Create client not using the dependency. | |
$client = new ClientImplementationWithOptionalDependency(); | |
// Create client using the dependency. | |
$client = new ClientImplementationWithMandatoryDependency(new UsefulDependencyImplementation()); | |
// Create client not using the dependency. | |
$client = new ClientImplementationWithMandatoryDependency(new DependencyNullImplementation()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment