PluginProbe
UpStream: a Project Management Plugin for WordPress / 2.1.0
UpStream: a Project Management Plugin for WordPress v2.1.0
trunk 1.39.0 1.39.1 1.39.2 1.39.3 2.0.7 2.1.0
upstream / includes / trait-up-singleton.php

trait-up-singleton.php in UpStream: a Project Management Plugin for WordPress 2.1.0, at includes/trait-up-singleton.php

104 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Trait that abstracts the Singleton design pattern.
4 *
5 * @package UpStream\Traits
6 */
7
8 namespace UpStream\Traits;
9
10 // Prevent direct access.
11 if ( ! defined( 'ABSPATH' ) ) {
12 exit;
13 }
14
15 /**
16 * Trait that abstracts the Singleton design pattern.
17 *
18 * @package UpStream
19 * @subpackage Traits
20 * @author UpStream <https://upstreamplugin.com>
21 * @copyright Copyright (c) 2018 UpStream Project Management
22 * @license GPL-3
23 * @since 1.11.0
24 */
25 trait Singleton {
26
27 /**
28 * The singleton class's instance.
29 *
30 * @var \ReflectionClass
31 *
32 * @since 1.11.0
33 * @access private
34 * @static
35 */
36 private static $instance = null;
37
38 /**
39 * Retrieve the singleton instance.
40 * If the singleton it's not loaded, it will be initialized first.
41 *
42 * @since 1.11.0
43 * @static
44 *
45 * @return \ReflectionClass
46 */
47 public static function getInstance() { // phpcs:ignore
48 // Ensure the singleton is loaded.
49 self::instantiate();
50
51 return self::$instance;
52 }
53
54 /**
55 * Initializes the singleton if it's not loaded yet.
56 *
57 * @since 1.11.0
58 * @static
59 * @final
60 *
61 * @uses \ReflectionClass
62 */
63 final public static function instantiate() {
64 if ( empty( self::$instance ) ) {
65 $reflection = new \ReflectionClass( __CLASS__ );
66 self::$instance = $reflection->newInstanceArgs( func_get_args() );
67 }
68 }
69
70 /**
71 * Prevent the class instance being serialized.
72 *
73 * @since 1.11.0
74 * @final
75 *
76 * @throws \Exception Exception.
77 */
78 final public function __sleep() {
79 throw new \Exception( 'You cannot serialize a singleton.' );
80 }
81
82 /**
83 * Prevent the class instance being unserialized.
84 *
85 * @since 1.11.0
86 * @final
87 *
88 * @throws \Exception Exception.
89 */
90 final public function __wakeup() {
91 throw new \Exception( 'You cannot unserialize a singleton.' );
92 }
93
94 /**
95 * Prevent the class instance being cloned.
96 *
97 * @since 1.11.0
98 * @final
99 */
100 final public function __clone() {
101 // Do nothing.
102 }
103 }
104