The primary objective of establishing a PDO connection is to create and maintain a single, reusable connection for each database while ensuring the connection is configured correctly.
1. Anonymous Function for Connection Initialization:
$provider = function() { $instance = new PDO('mysql:......;charset=utf8', 'username', 'password'); $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $instance; };
This anonymous function serves as the data provider for the factory, creating a PDO instance with appropriate settings.
2. Factory Pattern for Connection Management and Distribution:
class StructureFactory { protected $provider = null; protected $connection = null; public function __construct(callable $provider) { $this->provider = $provider; } public function create($name) { if ($this->connection === null) { $this->connection = call_user_func($this->provider); } return new $name($this->connection); } }
The factory ensures that the connection is established only when needed and provides a central location for customization and configuration.
3. Implementation:
In a separate file or at a later point in the same file:
$factory = new StructureFactory($provider); $something = $factory->create('Something'); $foobar = $factory->create('Foobar');
This approach provides a centralized and efficient way to handle PDO connections, guaranteeing that the connection is established correctly and made available to different classes as needed.
The above is the detailed content of How to Efficiently Manage PDO Database Connections Using the Factory Pattern?. For more information, please follow other related articles on the PHP Chinese website!