MySQL connection: globally or in object?

后端 未结 4 1380
逝去的感伤
逝去的感伤 2021-01-18 07:23

I have two PHP classes. One is for connecting to the database, building queries, executing them, and disconnecting from the database. The other class is for users: adding th

4条回答
  •  醉酒成梦
    2021-01-18 08:10

    Definitely keep track of and reuse a single connection in your base DB class. The above is a good example of creating and returning that connection as needed from the DB class.

    To make accessing that connection easier from your actual objects, you could then create a base object class (called DBable or something) which calls getDb in its constructor and assign that to a local $db variable inside that class. Then, all your objects which need database access can extend that DBable class, and always have a $db reference available implicitly without needing to remember to call getDb everywhere.

提交回复
热议问题