Created
June 5, 2016 19:01
-
-
Save jdavidlists/f2abeaefa58a9a823f71bb42fbd3f49d to your computer and use it in GitHub Desktop.
PHP god object
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 | |
class Database { | |
function queryOne( ... $x ) { | |
// Real object would prepare bound SQL and look up in the database. | |
return "blue"; | |
} | |
} | |
class GenericRow { | |
function __construct( GenericTable $table, $key ) { | |
$this->table = $table; | |
$this->key = $key; | |
} | |
function get( $field ) { | |
return $this->table->getField( $this->key, $field ); | |
} | |
} | |
class HouseRow extends GenericRow { | |
function getColor() { | |
return parent::get( "color" ); | |
} | |
function setColor( $color ) { | |
parent::set( "color", $color ); | |
} | |
} | |
class GenericTable { | |
function __construct( $database, $table_name, $key_name ) { | |
$this->database = $database; | |
$this->table_name = $table_name; | |
$this->key_name = $key_name; | |
} | |
function getField( $key, $field ) { | |
return $this->database->queryOne( | |
"SELECT % FROM {$this->table_name} WHERE {$key_name} = %", | |
$field, $key | |
); | |
} | |
} | |
class HouseTable extends GenericTable { | |
function __construct ( $god ) { | |
parent::__construct( $god->getDatabase(), "Houses", "pkHouse" ); | |
$this->god = $god; | |
} | |
function getObj( $key ) { | |
return new HouseRow( $this, $key ); | |
} | |
} | |
class GodObject { | |
function __construct( $database ) { | |
$this->database = $database; | |
} | |
function getDatabase() { | |
return $this->database; | |
} | |
function getHouseTable() { | |
return new HouseTable( $this ); | |
} | |
function getSessionData( $name ) { | |
// Would come from $_GET or something. | |
return 1; | |
} | |
} | |
abstract class WebPage { | |
function __construct() { | |
$this->database = new Database( "connection_info" ); | |
$this->god = new GodObject( $this->database ); | |
} | |
abstract function render(); | |
} | |
class ViewHouseColorPage extends WebPage { | |
function render() { | |
$house_id = $this->god->getSessionData( 'house_id' ); | |
$house_table = $this->god->getHouseTable(); | |
$house = $house_table->getObj( $house_id ); | |
echo "<p>Your house color is ", $house->getColor(), ".</p>"; | |
} | |
} | |
$page = new ViewHouseColorPage; | |
$page->render(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment