How can PHP developers ensure that objects set in a registry are available for use throughout the application?
To ensure that objects set in a registry are available throughout the application, PHP developers can use a singleton pattern to create a centralized registry class. This class can store objects in an associative array and provide methods to set and retrieve objects from the registry.
class Registry {
private static $instance;
private $registry = [];
private function __construct() {}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function set($key, $value) {
$this->registry[$key] = $value;
}
public function get($key) {
return $this->registry[$key] ?? null;
}
}
// Example usage
$registry = Registry::getInstance();
$registry->set('db', new Database());
$db = $registry->get('db');
Related Questions
- What are some best practices for handling SQL queries within nested loops in PHP to avoid performance issues and improve code readability?
- What are some common functions in PHP that can be used to sort and manipulate arrays of data efficiently?
- What are some best practices for handling multiple search terms and switching between "AND" and "OR" operations in PHP text file search scripts?