Skip to content

Instantly share code, notes, and snippets.

@GodsBoss
Created April 16, 2011 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GodsBoss/923547 to your computer and use it in GitHub Desktop.
Save GodsBoss/923547 to your computer and use it in GitHub Desktop.
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