目标
正如我所看到的,在这种情况下,您的目标是双重的:
- 为每个数据库创建并维护一个/可重复使用的连接
- 确保已正确建立连接
解
我建议同时使用匿名函数和工厂模式来处理PDO连接。它的用法如下所示:
$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 );然后在其他文件中或在同一文件中的较低文件中:
$something = $factory->create('Something');$foobar = $factory->create('Foobar');工厂本身应如下所示:
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 ); }}这种方式将使您拥有集中式的结构,从而确保仅在需要时才创建连接。这也将使单元测试和维护过程变得更加容易。
在这种情况下,提供程序将在引导阶段找到。这种方法还将提供一个清晰的位置,用于定义配置,以用于连接到数据库。
请记住,这是一个 极其简化的示例 。您还可以从观看以下两个视频中受益:
- 全球州和单身人士
- 不要找东西!
另外,我强烈建议您阅读有关PDO使用的适当教程(在线上有不良教程的日志)。



