Last active
December 29, 2015 17:09
-
-
Save k0d/7702433 to your computer and use it in GitHub Desktop.
Singletons, with Dependancy Injection and unit test support!
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 | |
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; | |
} | |
} |
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 | |
final class Singleton_Demo extends Abstract_Demo { | |
use Singleton; | |
} |
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 | |
interface Writer { | |
function write( $file, $message ); | |
// These methods will be used to demonstrate state | |
function increment( $step ); | |
function get_counter(); | |
} |
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 | |
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