Created
September 21, 2014 22:02
-
-
Save thefuxia/63f0a524ee881595a6bf to your computer and use it in GitHub Desktop.
Simple decorator pattern example
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 # -*- coding: utf-8 -*- | |
interface Url { | |
public function get_url(); | |
} | |
class Basic_Url implements Url { | |
private $url; | |
public function __construct( $url ) { | |
$this->url = $url; | |
} | |
public function get_url() { | |
return $this->url; | |
} | |
} | |
/** | |
* Changes the the URL to be without protocol. | |
*/ | |
class Url_Decorator implements Url { | |
private $url; | |
public function __construct( Url $url ) { | |
$string = $url->get_url(); | |
$host = parse_url( $string, PHP_URL_HOST ); | |
if ( $host === $_SERVER[ 'HTTP_HOST' ] ) | |
$this->url = preg_replace( '~^https?:~', '', $string ); | |
else | |
$this->url = $string; | |
} | |
public function get_url() { | |
return $this->url; | |
} | |
} | |
class Link_Builder { | |
private $url; | |
public function __construct( Url $url ) { | |
$this->url = $url; | |
} | |
public function get_link() { | |
return sprintf( '<a href="%1$s">%1$s</a>', $this->url->get_url() ); | |
} | |
} | |
$basic_url = new Basic_Url( 'http://' . $_SERVER['HTTP_HOST'] . '/foo' ); | |
$link_1 = new Link_Builder( | |
$basic_url | |
); | |
$link_2 = new Link_Builder( new Url_Decorator( $basic_url ) ); | |
// normal | |
print $link_1->get_link() . '<br>'; | |
print $link_2->get_link() . '<br>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment