Skip to content

Instantly share code, notes, and snippets.

@k0d
Last active December 29, 2015 17:09
Show Gist options
  • Save k0d/7702433 to your computer and use it in GitHub Desktop.
Save k0d/7702433 to your computer and use it in GitHub Desktop.
Singletons, with Dependancy Injection and unit test support!
<?php
abstract class AbstractWriter implements Writer {
protected $counter = 0;
public function write( $file, $message ) {
$fp = fopen( $file, 'a' );
fwrite( $fp, $message . "\r\n" );
fclose( $fp );
}
public function increment( $step ) {
$this->counter += $step;
}
public function get_counter() {
return $this->counter;
}
}
<?php
final class Singleton_Demo extends Abstract_Demo {
use Singleton;
}
<?php
interface Writer {
function write( $file, $message );
// These methods will be used to demonstrate state
function increment( $step );
function get_counter();
}
<?php
trait Singleton {
protected static $instance;
protected function __construct() {}
/**
* Return class instance
* @return object
**/
public static function Instance() {
if(!(static::$instance instanceof static)) {
static::$instance = new static();
}
return static::$instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment