refactor Loader@load

loader-rework
fadrian06 3 days ago
parent d196cc09e1
commit 6acbdb2082

@ -6,6 +6,7 @@ namespace flight\core;
use Closure; use Closure;
use Exception; use Exception;
use Throwable;
/** /**
* Responsible for loading objects. It maintains a list of reusable class * Responsible for loading objects. It maintains a list of reusable class
@ -66,38 +67,34 @@ class Loader
/** /**
* Loads a registered class. * Loads a registered class.
* *
* @param string $name Method name * @param string $name Method name.
* @param bool $shared Shared instance * @param bool $shared Shared instance.
*
* @throws Exception
*
* @return ?object Class instance * @return ?object Class instance
* @throws Throwable
*/ */
public function load(string $name, bool $shared = true): ?object public function load(string $name, bool $shared = true): ?object
{ {
$obj = null; $obj = null;
if (isset($this->classes[$name])) { if (!isset($this->classes[$name])) {
[0 => $class, 1 => $params, 2 => $callback] = $this->classes[$name]; return null;
}
$exists = isset($this->instances[$name]); [$class, $params, $callback] = $this->classes[$name];
$exists = isset($this->instances[$name]);
if ($shared) { if ($shared) {
$obj = ($exists) ? $obj = $exists
$this->getInstance($name) : ? $this->getInstance($name)
$this->newInstance($class, $params); : $this->newInstance($class, $params);
if (!$exists) { $this->instances[$name] ??= $obj;
$this->instances[$name] = $obj; } else {
} $obj = $this->newInstance($class, $params);
} else { }
$obj = $this->newInstance($class, $params);
}
if ($callback && (!$shared || !$exists)) { if ($callback && (!$shared || !$exists)) {
$ref = [&$obj]; $callback($obj);
\call_user_func_array($callback, $ref);
}
} }
return $obj; return $obj;

Loading…
Cancel
Save