lithium\core\Libraries::instance()
Uses service location (i.e. Libraries::locate()
) to look up a named class of a particular
type, and creates an instance of it, and passes an array of parameters to the constructor.
If the given class can't be found, an exception is thrown.
Parameters
-
string
$type
The type of class as defined by
Libraries::$_paths
. -
string|object
$name
The un- or fully namespaced name of the class to instantiate or a name in the $classes array. Alternatively an already instantiated object, which will be returned unmodified.
-
array
$config
An array of constructor parameters to pass to the class.
-
array
$classes
Map of short names to fully namespaced classes or instantiated objects, to use for resolving short names.
Returns
objectIf the class is found, returns an instance of it.
Filter
This method can be filtered.
Source
public static function instance($type, $name, array $options = [], array $classes = []) {
$params = compact('type', 'name', 'options', 'classes');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$name = $params['name'];
$type = $params['type'];
$classes = $params['classes'];
if (is_string($name) && isset($classes[$name])) {
$name = $classes[$name];
}
if (is_object($name)) {
return $name;
}
if (!$name && !$type) {
$message = "Invalid class lookup: `\$name` and `\$type` are empty.";
throw new ClassNotFoundException($message);
}
if (!is_string($type) && $type !== null && !isset(static::$_paths[$type])) {
throw new ClassNotFoundException("Invalid class type `{$type}`.");
}
if (!$class = static::locate($type, $name)) {
throw new ClassNotFoundException("Class `{$name}` of type `{$type}` not found.");
}
if (!(is_string($class) && class_exists($class))) {
throw new ClassNotFoundException("Class `{$name}` of type `{$type}` not defined.");
}
return new $class($params['options']);
});
}