如何使用单个 MySql 连接与多个 PHP 对象。
我已经阅读了很多这方面的例子,但是我读得越多,我就越感到困惑(抱歉!)。我的首要任务是保持简单和高效。生成单个 MySql 连接并与多个 PHP 对象共享。
// open a db connection
$dbc = new PDO(.......);
// allow multiple objects to use the same connection
$object_1 = new class_1($dbc);
$object_2 = new class_2($dbc);
$object_3 = new class_3($dbc);
// or should it be passed this way?
$object_1->connection($dbc);
$object_2->connection($dbc);
$object_3->connection($dbc);
// or should each of the classes be getting the connection
// from a singleton type db object?
// should each object be an extesion of a db class?
// or is there something else I need to consider?
I have been going through lots of examples on this, but the more I read the more I get confused (sorry!). My priority is keep it simple and efficient. Generate a single MySql connection and share it with multiple PHP objects.
// open a db connection
$dbc = new PDO(.......);
// allow multiple objects to use the same connection
$object_1 = new class_1($dbc);
$object_2 = new class_2($dbc);
$object_3 = new class_3($dbc);
// or should it be passed this way?
$object_1->connection($dbc);
$object_2->connection($dbc);
$object_3->connection($dbc);
// or should each of the classes be getting the connection
// from a singleton type db object?
// should each object be an extesion of a db class?
// or is there something else I need to consider?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这两种方法都是正确的,但如果对象工作需要数据库连接,则将其传递给构造函数是首选方法。
有关此主题的更多信息,请参阅有关依赖注入的文章。
例如:http://martinfowler.com/articles/injection.html
Both of these are correct, although if database connection is necessary for an object to work, then passing it to constructor is the preferred way.
For more information on this topic look up articles on Dependency Injection.
For example: http://martinfowler.com/articles/injection.html
我更喜欢将连接类设置为 Singlton :
I preffer to make Connection Class as Singlton :