What is the purpose of using a Registry in PHP for global availability of classes, and how does it compare to Dependency Injection?
Using a Registry in PHP allows for global availability of classes by storing instances of objects in a central location, making them easily accessible throughout the application. This can be useful for sharing common objects or resources across different parts of the codebase. On the other hand, Dependency Injection is a design pattern where dependencies are provided to a class through its constructor or methods, allowing for better code organization, testability, and flexibility.
class Registry {
private static $instances = [];
public static function set($key, $value) {
self::$instances[$key] = $value;
}
public static function get($key) {
return self::$instances[$key];
}
}
// Usage example
Registry::set('db', new Database());
$db = Registry::get('db');
Related Questions
- How can special characters be prioritized at the beginning of a sorted list in PHP?
- How can PHP be utilized to dynamically render content on a webpage based on user interactions or input?
- What are some alternative approaches to transmitting large amounts of data in PHP besides using GET or POST methods?