Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created September 4, 2017 19:38
Show Gist options
  • Save joduplessis/1c31871ba29fc36e2182f32c78223c03 to your computer and use it in GitHub Desktop.
Save joduplessis/1c31871ba29fc36e2182f32c78223c03 to your computer and use it in GitHub Desktop.
Design pattern examples using PHP. These are a bit dated, but hey. It's a gist.
<h1>Design Patterns</h1>
<h2>Singleton classes ( persist one object over multiple calls )</h2>
<?php
class Database
{
private $connection = null ;
public static function getDB()
{
static $database = null;
if ( $database == null )
{
$database = new Database();
}
return $database;
}
private function __construct()
{
$this->connection = "Hurray, a database connection!" ;
}
public function databaseConnection()
{
return $this->connection;
}
}
echo Database::getDB()->databaseConnection() ;
?>
<h2>Creating a factory ( seperating the logic gruntwork from the "creating"</h2>
<?php
interface BirthdaySong {
function createSong();
}
class Song implements BirthdaySong {
private $name ;
public function __construct( $name_parameter )
{
$this->name = $name_parameter ;
}
public function createSong()
{
$song = 'Happy birthday to you! <br/>' ;
$song .= 'Happy birthday to you! <br/>' ;
$song .= 'Happy birthday dear ' . $this->name ;
$song .= '! <br/>' ;
$song .= 'Happy birthday to you! <br/>' ;
return $song;
}
}
class SongFactory {
public static function Create( $name )
{
return new Song( $name );
}
}
$userSong = SongFactory::Create( "Tony" );
echo $userSong->createSong() ;
?>
<h2>States ( very simple example of altering object states based on calls, and call order )</h2>
<?php
class FluxCapacitor {
private $state;
public function timeJump()
{
if ( $this->state == "ready" )
{
echo("Jumping to 1985<br/>");
} else if ( $this->state == "nopower" ) {
echo("Needs more Plutonium<br/>");
}
}
public function __construct()
{
$this->state = "nopower";
}
public function nuke()
{
if ( $this->state == "ready" )
{
echo("Already has Plutonium");
} else {
$this->state = "ready" ;
echo("Added Plutonium<br/>");
}
}
}
$delorean = new FluxCapacitor();
$delorean->timeJump();
$delorean->nuke();
$delorean->timeJump();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment