Last active
December 5, 2018 08:31
-
-
Save PatelUtkarsh/f7644095001eae1d8f64e6d5b96af4e1 to your computer and use it in GitHub Desktop.
Singletone trait
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 | |
/** | |
* The Demo class. | |
* | |
* @package xyz | |
*/ | |
namespace UtkarshPatel\Demo | |
/** | |
* Class Demo | |
*/ | |
class Demo { | |
use UtkarshPatel\Traits\Singleton; | |
/** | |
* Initialization. | |
*/ | |
protected function init() { | |
/* | |
* Add everything that you usually add to constructor | |
* In case of inheritance parent class should have this trait and not child else it not work since constructor is not calling parent. | |
*/ | |
add_filter( 'init', array( $this, 'my_method' ) ); | |
} | |
public function my_method() { | |
} | |
} |
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 | |
* | |
* @package XYZ | |
*/ | |
namespace UtkarshPatel\Traits; | |
/** | |
* Trait Singleton | |
*/ | |
trait Singleton { | |
/** | |
* Instance of class. | |
* | |
* @var $instance | |
*/ | |
protected static $instance; | |
/** | |
* Create instance only once. | |
* | |
* @return static Current class object. | |
*/ | |
final public static function get_instance() { | |
return isset( static::$instance ) | |
? static::$instance | |
: static::$instance = new static(); | |
} | |
/** | |
* Singleton constructor. | |
*/ | |
final private function __construct() { | |
$this->init(); | |
} | |
/** | |
* Action / Filters to be declare here. | |
*/ | |
protected function init() { | |
} | |
/** | |
* Make private magic method wakeup. | |
*/ | |
final private function __wakeup() { | |
} | |
/** | |
* Make private magic method clone. | |
*/ | |
final private function __clone() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment