Singleton pattern in PHP
What is the Singleton pattern
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
Why we use it
How Use it
Example :
领英推荐
we'll use a DatabaseConnection class as a Singleton website to manage a single database connection throughout the website
class DatabaseConnection {
private static $instance;
private $connection;
private function __construct() {
// database connection
$this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
public static function getInstance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
// Example usage in a web pages:
$database = DatabaseConnection::getInstance();
$connection = $database->getConnection();
// Now you can use $connection to perform database queries throughout your webpage
// without establishing a new connection every time.
Another example we can use for session management in website
class AuthManager {
public static function login($username, $password) {
// authentication logic, check credentials against a database
if ($username === 'demo' && $password === 'password') {
$_SESSION['user'] = $username;
return true;
}
return false;
}
public static function logout() {
// Perform logout logic, destroy the session
session_destroy();
}
public static function isAuthenticated() {
// Check if a user is authenticated
return isset($_SESSION['user']);
}
public static function getCurrentUser() {
// Get the current user from the session
return $_SESSION['user'] ?? null;
}
}
// Usage example in web pages:
session_start();
// Perform login
AuthManager::login('demo', 'password');
// Check authentication status
if (AuthManager::isAuthenticated()) {
echo "Welcome, " . AuthManager::getCurrentUser();
} else {
echo "Not authenticated. Redirect to login page.";
}
above example are simple.