PluginProbe
ZIP AI – AI Website Builder & AI Agent (Beta) / 0.0.4
ZIP AI – AI Website Builder & AI Agent (Beta) v0.0.4
0.0.10 0.0.9 trunk 0.0.4 0.0.5 0.0.6 0.0.7 0.0.8
zip-ai / classes / core / container.php

container.php in ZIP AI – AI Website Builder & AI Agent (Beta) 0.0.4, at classes/core/container.php

103 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Dependency Injection Container.
4 *
5 * @package zip-ai
6 */
7
8 namespace ZipAI\Classes\Core;
9
10 defined( 'ABSPATH' ) || exit;
11
12 /**
13 * Container Class.
14 */
15 class Container {
16
17 /**
18 * The bindings.
19 *
20 * @var array
21 */
22 protected $bindings = array();
23
24 /**
25 * The shared instances.
26 *
27 * @var array
28 */
29 protected $instances = array();
30
31 /**
32 * Register a binding with the container.
33 *
34 * @param string $abstract The abstract type or name.
35 * @param mixed $concrete The concrete implementation or closure.
36 * @param bool $shared Whether the binding is shared (singleton).
37 */
38 public function bind( $abstract, $concrete = null, $shared = false ) {
39 if ( is_null( $concrete ) ) {
40 $concrete = $abstract;
41 }
42
43 $this->bindings[ $abstract ] = array(
44 'concrete' => $concrete,
45 'shared' => $shared,
46 );
47 }
48
49 /**
50 * Register a shared binding in the container.
51 *
52 * @param string $abstract The abstract type or name.
53 * @param mixed $concrete The concrete implementation or closure.
54 */
55 public function singleton( $abstract, $concrete = null ) {
56 $this->bind( $abstract, $concrete, true );
57 }
58
59 /**
60 * Resolve the given type from the container.
61 *
62 * @param string $abstract The abstract type or name.
63 * @return mixed
64 */
65 public function make( $abstract ) {
66 // Return shared instance if it exists.
67 if ( isset( $this->instances[ $abstract ] ) ) {
68 return $this->instances[ $abstract ];
69 }
70
71 // If not bound, try to instantiate directly.
72 if ( ! isset( $this->bindings[ $abstract ] ) ) {
73 return new $abstract();
74 }
75
76 $concrete = $this->bindings[ $abstract ]['concrete'];
77 $object = null;
78
79 if ( $concrete instanceof \Closure ) {
80 $object = $concrete( $this );
81 } else {
82 $object = $this->make( $concrete );
83 }
84
85 // Save shared instance.
86 if ( $this->bindings[ $abstract ]['shared'] ) {
87 $this->instances[ $abstract ] = $object;
88 }
89
90 return $object;
91 }
92
93 /**
94 * Check if the given abstract type has been bound.
95 *
96 * @param string $abstract The abstract type or name.
97 * @return bool
98 */
99 public function has( $abstract ) {
100 return isset( $this->bindings[ $abstract ] ) || isset( $this->instances[ $abstract ] );
101 }
102 }
103