Create a gist now

Instantly share code, notes, and snippets.

Simple decorator pattern example
<?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