Home >Backend Development >PHP Tutorial >How to Efficiently Manage PDO Database Connections Using a Factory Pattern?
To ensure optimal performance, it is crucial to establish a single, reusable connection to the database. This can be accomplished through the use of an anonymous function and factory pattern. The following code illustrates this approach:
$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; }; $factory = new StructureFactory($provider);
In a separate file or further down in the current file, you can initialize your database structures:
$something = $factory->create('Something'); $foobar = $factory->create('Foobar');
The factory class would follow this structure:
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); } }
This approach offers several advantages:
The above is the detailed content of How to Efficiently Manage PDO Database Connections Using a Factory Pattern?. For more information, please follow other related articles on the PHP Chinese website!