Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Verschiedene Implementierungen einer Client-Klasse mit einer optionalen Abhängigkeit.
<?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