What are some best practices for implementing a Registry in PHP to avoid potential pitfalls?
When implementing a Registry in PHP, it is important to avoid global variables and instead use a singleton pattern to ensure only one instance of the Registry is created. Additionally, it is crucial to clearly define and document the keys and values stored in the Registry to prevent confusion and misuse. Lastly, be cautious of overusing the Registry pattern, as it can lead to tightly coupled code and make debugging more difficult.
class Registry {
private static $instance;
private $data = [];
private function __construct() {}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Registry();
}
return self::$instance;
}
public function set($key, $value) {
$this->data[$key] = $value;
}
public function get($key) {
return $this->data[$key] ?? null;
}
}
// Example usage
$registry = Registry::getInstance();
$registry->set('key', 'value');
echo $registry->get('key');