class-ldlms-factory.php
2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
/**
* LearnDash Factory Class.
*
* This is an abstract class for Course Posts, User Progression, etc.
*
* @since 2.5.0
* @package LearnDash
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'LDLMS_Factory' ) ) {
/**
* Class for LearnDash LMS Factory.
*
* @since 2.5.0
*/
abstract class LDLMS_Factory {
/**
* Static array of object instances.
*
* @var array $instances.
*/
protected static $instances = array();
/**
* Public constructor for class.
*
* @since 2.5.0
*/
public function __construct() {
}
/**
* Get the current instance of this class or new.
*
* @since 2.5.0
*
* @param string $model Unique identifier for model.
* @param string $key Unique identifier for instance.
* @param bool $add_instance Optional. Whether to add an instance. Default true.
*/
protected static function get_instance( $model = '', $key = null, $add_instance = true ) {
$model = esc_attr( $model );
$key = esc_attr( $key );
if ( ( ! empty( $model ) ) && ( ! empty( $key ) ) ) {
if ( isset( self::$instances[ $model ][ $key ] ) ) {
return self::$instances[ $model ][ $key ];
} elseif ( true === $add_instance ) {
return self::add_instance( $model, $key );
}
}
}
/**
* Add Model instance.
*
* @since 2.5.0
*
* @param string $model Class name to add.
* @param int|string $key Unique key for instance.
* @param mixed ...$args Args passed to class constructor.
*/
protected static function add_instance( $model = '', $key = null, ...$args ) {
$model = esc_attr( $model );
$key = esc_attr( $key );
if ( ( ! empty( $model ) ) && ( class_exists( $model ) ) && ( ! empty( $key ) ) ) {
if ( ! isset( self::$instances[ $model ] ) ) {
self::$instances[ $model ] = array();
}
if ( isset( self::$instances[ $model ][ $key ] ) ) {
return self::$instances[ $model ][ $key ];
} else {
try {
$class = new ReflectionClass( $model );
self::$instances[ $model ][ $key ] = $class->newInstanceArgs( $args );
return self::$instances[ $model ][ $key ];
} catch ( LDLMS_Exception_NotFound $e ) {
return null;
}
}
}
}
/**
* Remove Model instance.
*
* @since 2.5.0
*
* @param string $model Class name to add.
* @param int|string $key Unique ID for instance.
*/
protected static function remove_instance( $model = '', $key = null ) {
$model = esc_attr( $model );
$key = esc_attr( $key );
if ( ( ! empty( $model ) ) && ( class_exists( $model ) ) && ( ! empty( $key ) ) ) {
if ( isset( self::$instances[ $model ][ $key ] ) ) {
unset( self::$instances[ $model ][ $key ] );
return true;
}
}
}
}
}