singleton in abstract class php - php

I have a simple question. I use a singleton which implements an abstract class. Is it possible to put the getInstance() Method and the variable $_instance in the abstract class instead of the concrete one I want to create?
Here's my code:
<?php
class Command_Log extends Command_Abstract {
private static $_instance=null;
public static function getInstance() {
if (self::$_instance==null)
self::$_instance=new self();
return self::$_instance;
}
protected function realExecute() {
}
protected function realSimulate($fileHandle) {
}
}
and
<?php
abstract class Command_Abstract implements Command_Interface {
protected $_data=array();
//private static $_instance=null;
protected $_isExecuted=false;
protected $_execute=false;
public function enableExecute() {
$this->_execute=true;
return $this;
}
protected function __construct() {
}
protected function __clone() {}
public function addData($data) {
array_push($this->_data,$data);
return $this;
}
abstract protected function realExecute();
abstract protected function realSimulate($fileHandle);
public function execute() {
if(!$this->_isExecuted && $this->_execute) {
$this->_isExecuted = true;
$this->realExecute();
}
}
public function simulate() {
$exitSystem = false;
if(!$this->_isExecuted && $this->_execute) {
$this->_isExecuted = true;
$exitSystem = $this->realSimulate($fh);
}
}
return $exitSystem;
}
}
I have many implementations of the the commands, so I don't want redundant code everywhere in my implementations. Is it possible to put these two things in the abstract class, if yes please tell me how.
If not please explain it to me why it isnt possbile. Or if I need to change something to do it, anyhow.
regards

YES WE CAN!
I have a class called Singleton that is abstract... and many classes that extends that Singleton class... this is the code:
abstract class Singleton {
private static $instances = array();
final private function __construct($_params) {
$class = get_called_class();
if (array_key_exists($class, self::$instances))
throw new Exception('An instance of '. $class .' already exists !');
//static::initialize(); //In PHP 5.3
$this->initialize($_params);
}
final private function __clone() { }
abstract protected function initialize();
public static function getInstance($_params=array()) {
$class = get_called_class();
if (array_key_exists($class, self::$instances) === false){
self::$instances[$class] = new $class($_params);
}
return self::$instances[$class];
}
}
and (for example) the class DBConnection that extends from Singleton
class DBConnection extends Singleton{
private $connexion_pdo=null;
protected function initialize(){
//connect to the DB
$this->connexion_pdo = blablalba;
}
}
although there are some problems in php 5.2.. specially with the function get_called_class() and the static::initialize()
You could also check the php site for patterns... there are lots of contributions for the singleton
Good Luck

Related

Initiating a class globally

To be specific, i have a two class Request and Utils,
class Request
{
public function __construct()
{
//constructor method
}
public function request()
{
$utils=new Utils;
$consolidated_errors=$utils->array_remove_empty($all_params_error);
}
public function process()
{
$utils=new Utils;
$consolidated_errors=$utils->another_method($all_params_error);
}
}
And class Utils,
class Utils
{
public function __construct()
{
//constructor method
}
public function array_remove_empty()
{
//returns a variable.
}
public function another_method()
{
//returns a variable.
}
}
you can see that i am initializing the class two times in request class , and my question is that any way initializing the class globally and using through out the class?
You are looking for Singleton pattern
Following demonstrate very basic Singleton example for your class
public class Utils {
private static Utils uniqInstance;
private Utils() {
}
public static synchronized Utils getInstance() {
if (uniqInstance == null) {
uniqInstance = new Utils();
}
return uniqInstance;
}
// other useful methods here
}
get the instance using static-factory pattern
The above code does not look like Java to me, but anyway,
You could create the class at a class level private Utils myUtuils = new Utils ();
or
have the class as a static class and then just use it directly in your method
public function process()
{
consolidated_errors= Utils.another_method($all_params_error);
}
}

php enforce type of extending class

Is there any way in php to make sure that a class can be extended by one and only one class?
I have some code that illustrates what I'm trying to do, basically I have a DB manager class and a DB query class that is extended by the manager class. What I'd like to do is make sure that the DB query class can only be used by the DB manager class.
The code below works, but it seems very rough. In the code I delcare the query class abstract with a single abstract function that checks the classname, or I could simply declare all of the Manager functions as abstract in the query class (which seems hacky). If there is a simpler way to do this than my code below that would be very useful...
abstract class DB_Query {
private static $HOST = 'localhost';
private static $USERNAME = 'guest';
private static $PASSWORD = 'password';
private static $DATABASE = 'APP';
//////////
/* USING ABSTRACT FUNCTION HERE TO ENFORCE CHILD TYPE */
abstract function isDB();
/* OR USING ALTERNATE ABSTRACT TO ENFORE CHILD TYPE */
abstract function connect();
abstract function findConnection();
abstract function getParamArray();
//////////
private function __construct() { return $this->Connect(); }
public function Read($sql) { //implementation here }
public function Query($sql) { //implementation here }
public function Fetch($res, $type='row', $single='true') { //implementation here }
}
class DB extends DB_Query {
public $connections = array();
public static $instance;
public function isDB() {
if (get_parent_class() === 'Database' && get_class($this)!=='DB') {
throw new \Exception('This class can\'t extend the Database class');
}
}
public function connect($host=null,$user=null,$pass=null,$db=null) { //implementation here }
function findConnection($user, $password=null) { //implementation here }
public function getParamArray($param) {}
public function threadList() {}
public function getThread($threadId=null) {}
public static function Singleton() { //implementation here }
private function __construct() { //implementation here }
}
I would go after marking the constructor of DB_Query as final and implementing it the way that it checks the instance and fires some exception. Something like this
class Base {
final function __construct() {
if (!$this instanceof Base && !$this instanceof TheChosenOne) {
throw new RuntimeException("Only TheChosenOne can inherit Base");
}
/**
* use this function as constructor
*/
$this->__internal_base_construct();
}
protected function __internal_base_construct() {
// constructor code
}
}
But your problem is rather strange and kind of breaking the idea of OOP in several ways. Just combine it into a single class and use final class directive.
http://php.net/manual/en/language.oop5.final.php
class Database_Query extends Database {
public static $instance;
public function Query($sql) {}
public function Fetch($res, $type='row', $single='true') {}
public static function Singleton() {}
private function __construct() {
$this->link = $this->connect()->find('guest')->getLink();
}
}

Instance as a static class property

Is it possible to declare an instance of a class as a property in PHP?
Basically what I want to achieve is:
abstract class ClassA()
{
static $property = new ClassB();
}
Well, I know I can't do that, but is there any workaround beside always doing something like this:
if (!isset(ClassA::$property)) ClassA::$property = new ClassB();
you can use a singleton like implementation:
<?php
class ClassA {
private static $instance;
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new ClassB();
}
return self::$instance;
}
}
?>
then you can reference the instance with:
ClassA::getInstance()->someClassBMethod();
An alternative solution, a static constructor, is something along the lines of
<?php
abstract class ClassA {
static $property;
public static function init() {
self::$property = new ClassB();
}
} ClassA::init();
?>
Please note that the class doesn't have to be abstract for this to work.
See also How to initialize static variables and https://stackoverflow.com/a/3313137/118153.
This is a few years old, but I just ran into a issue where I have a base class
class GeneralObject
{
protected static $_instance;
public static function getInstance()
{
$class = get_called_class();
if(!isset(self::$_instance))
{
self::$_instance = new $class;
}
return self::$_instance;
}
}
That has a Child Class
class Master extends GeneralObject
{
}
And another Child class
class Customer extends Master
{
}
But when I try to call
$master = Master::getInstance();
$customer = Customer::getInstance();
then $master will be Master as expected, but $customer will be Master because php uses the GeneralObject::$_instance for both Master and Customer
The only way I could achieve what I want was to change the GeneralObject::$_instance to be an array and adjust the getInstance() method.
class GeneralObject
{
protected static $_instance = array();
public static function getInstance()
{
$class = get_called_class();
if(!isset(self::$_instance[$class]))
{
self::$_instance[$class] = new $class;
}
return self::$_instance[$class];
}
}
I hope this helps someone else out there. Took me a few hours to debug what was going on.

PHP 5.3 Abstract singleton class and childrens?

i has singleton class with final static method "getInstance()":
<?php
abstract class Singleton
{
protected static $instances;
final public static function getInstance()
{
$class = get_called_class();
if(!isset(static::$instances[$class]))
static::$instances[$class] = new $class();
return static::$instances[$class];
}
}
And code like this:
<?php
class C1 extends Singleton { }
class C2 extends Singleton { }
C1::getInstance(); // Created C1 class
C2::getInstance(); // Still get C1 class, get_called_class() return C1 when i try get C2
What i'm do wrong?
The reason this isn't working is that you're not creating a $instance property for each of your subclasses. While using static:: and get_called_class() will access subclass members instead of superclass members, if the members don't exist in the subclass then they will fall back to the ones defined in the superclass. The result of this is that you'll end up getting the same member anyway.
Try defining your subclasses like this instead.
class C1 extends Singleton {
protected static $instances;
}
class C2 extends Singleton {
protected static $instances;
}
C1->getInstance();
C2->getInstance();
should be
C1::getInstance();
C2::getInstance();
The code
Update:
You don't need an array to hold the instances, instead, let the subclass the hold. Try the code below.
class Singleton
{
private function __construct(){}
protected static $instance;
final public static function getInstance()
{
$class = get_called_class();
if(!static::$instance)
static::$instance = new $class();
return static::$instance;
}
}
class C1 extends Singleton {
protected static $instance;
}
class C2 extends Singleton {
protected static $instance;
}
var_dump(C1::getInstance());
var_dump(C2::getInstance());
Try this abstract Singleton:
abstract class Singleton
{
private static $_instances = array();
public static function getInstance()
{
$class = get_called_class();
if (!isset(self::$_instances[$class])) {
self::$_instances[$class] = new $class();
}
return self::$_instances[$class];
}
}
I can't reproduce your problem:
var_dump(C1::getInstance());
var_dump(C2::getInstance());
gives:
object(C1)#1 (0) {
}
object(C2)#2 (0) {
}
As the var_dump output shows, the types are different (C1, then C2). Keep in mind that you need to invoke the getInstance() statically as it's a static function.
Next to that if you want to really implement the Singleton pattern in PHP, your abstract class is missing some important method definitions to make this more precise with PHP. See Patterns­PHP Manual.
Also in PHP you normally do not need a Singleton at all, inject dependencies instead which will make your code more fluent.
Hope this is helpful.
Working version of abstract singleton:
abstract class Singletone {
private static $_instance = NULL;
private function __construct(){}
public static function GetInstance() {
if( !static::$_instance ) {
static::$_instance = new static();
}
return static::$_instance;
}
}
The derived class must overwrite the $_instance
class DefaultRouter extends Singletone {
protected static $_instance = NULL;
}
There's no need to redefine the static $instance property in the child classes, just use the one defined in the superclass:
<?php
class Singleton
{
public static $Instance;
private function __construct() { }
public static function GetInstance() {
if(!Singleton::$Instance) {
Singleton::$Instance = new static();
}
return Singleton::$Instance;
}
}
class MyClass extends Singleton
{
public $field1;
public $field2;
public $field3;
public function __construct()
{
$this->field1 = "field1";
$this->field2 = "field2";
$this->field3 = "field3";
}
}
var_dump(Myclass::GetInstance());
?>
It outputs
object(MyClass)#1 (3) {
["field1"]=>
string(6) "field1"
["field2"]=>
string(6) "field2"
["field3"]=>
string(6) "field3"
}
https://eval.in/306503

Best practice to implement static class inheritance? (singleton)

From php manual:
[...] Static method calls are resolved at compile time.
When using an explicit class name the method is already identified completely and no
inheritance rules apply. If the call is done by self then self is translated to
the current class, that is the class the code belongs to.
Here also no inheritance rules apply [...]
..so im looking for a way to emulate the standard oop inheritance with static singleton.
Code explain better:
// Normal inheritance: my goal.
class Foo{
public function test(){
echo "Foo->test()\n";
}
}
class Bar extends Foo{
public function other_test()
{
echo "Bar->other_test()\n";
}
}
$obj = new Bar();
echo get_class($obj) . "\n";
$obj->test();
$obj->other_test();
/*
Output:
Bar
Foo->test()
Bar->other_test()
*/
// How i would love to do:
class Foo2{
public static function test2()
{
echo "Foo2::test2()\n";
}
// Singleton?
public static $_instance;
public static function get_instance()
{
if(is_null(self::$_instance))
{
self::$_instance = new self();
}
return self::$_instance;
}
}
class Bar2 extends Foo2{
public static function other_test2()
{
echo "Bar2::other_test2()\n";
}
}
$obj2 = Bar2::get_instance();
echo get_class($obj2) . "\n";
$obj2::test2();
$obj2::other_test2();
/*
Output:
Foo2
Foo2::test2()
Fatal error: Call to undefined method Foo2::other_test2()
*/
echo "\n-------\n";
// How im doing actually:
interface Foo3{
public static function get_instance();
}
class Bar3 implements Foo3{
// Singleton?
public static $_instance;
public static function get_instance()
{
if(is_null(self::$_instance))
{
self::$_instance = new self();
}
return self::$_instance;
}
public static function test3()
{
echo "Bar3::test3()\n";
}
public static function other_test3()
{
echo "Bar3::other_test3()\n";
}
}
$obj3 = Bar3::get_instance();
echo get_class($obj3) . "\n";
$obj3::test3();
$obj3::other_test3();
/*
Output:
Bar3
Foo3::test3()
Bar3::other_test3()
*/
The last 'way' force me to avoid the get_instance and static variables to be placed in the parent class, so I do not consider it as a best solution.. if for some reason my get_instance() function will change in the future, i dont want to edit all classes (inheritance! inheritance! we all want inheritance!)
So, is there a way or a best practices to solve this problem?
p.s: php5.3.2
The Singleton pattern in PHP is something like this:
class Singleton {
private static $instance = null;
// Constructor is private, so class cannot be instantiazed from outside
private function __construct() {
}
public static function getInstance() {
if (static::$instance === null) {
static::$instance = new Singleton();
}
return static::$instance;
}
public static function test() {
echo 'Singleton::test()';
}
public function __sleep() {
throw new Exception('Serialization is not alowed.');
}
public function __wakeup() {
throw new Exception('Serialization is not alowed.');
}
public function __clone() {
throw new Exception('Cloning is not alowed.');
}
}
For you is important that keyword static, then this:
class B extends Singleton {
public static function test2() {
echo 'B::test2()';
}
}
$b = B::getInstance();
B::test();
B::test2();
// Singleton::test()
// B::test()
Is this you looking for?

Categories