What are the best practices for making instances of handler classes accessible to all other classes in a PHP project?
To make instances of handler classes accessible to all other classes in a PHP project, one common approach is to use a design pattern like the Singleton pattern. This ensures that only one instance of the handler class is created and provides a global point of access to it. By using a static method to retrieve the instance, other classes can easily access the handler class without needing to create new instances.
class Handler {
private static $instance;
private function __construct() {
// private constructor to prevent instantiation
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new Handler();
}
return self::$instance;
}
public function handleRequest($request) {
// handle request logic
}
}
// Accessing the handler instance from other classes
$handler = Handler::getInstance();
$handler->handleRequest($request);
Related questions
-
preg_replace constants template
-
SQL injection security vulnerability GET method
-
data entry predefined separators text processing