Skip to content

Instantly share code, notes, and snippets.

@jdavidlists
Created June 5, 2016 19:01
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 jdavidlists/f2abeaefa58a9a823f71bb42fbd3f49d to your computer and use it in GitHub Desktop.
Save jdavidlists/f2abeaefa58a9a823f71bb42fbd3f49d to your computer and use it in GitHub Desktop.
PHP god object
<?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