MySQL connection: globally or in object?

后端 未结 4 1340
逝去的感伤
逝去的感伤 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 07:50

    In PHP, the best practice is to take the global approach. This is mainly due to the fact that repeated connects/disconnects to the MySQL server can cause a significant decrease in performance.

    In fact, though this may seem counter-intuitive, most PHP experts (including myself) recommend that you avoid using mysql_close() altogether, unless there's a pressing reason not to. This is because that is handled automatically in PHP's cleanup anyway, so adding mysql_close() just creates a further deterioration in performance.

    0 讨论(0)
  • 2021-01-18 07:50

    I'm debating whether I should connect to the database on the page globally and use that connection (passing the database object into the method of the user object), or whether I should connect and disconnect from the database from within the a user method itself.

    Stop debating. Make the database class available to the functions that need it and handle the connection transparently, so that you have one connection per request. Doing multiple connects / disconnects is superfluous and only creates too much work that does not need to be done.

    So actually you only need one connection variable (object). Make it available to the functions that need it (e.g. a database class that has it as a member) and you're fine. Whether or not you make that object globally available is your design decision.

    Additionally take a look into a pattern called table data gateway and / or the active record pattern. Probably that's what you do with your user object, so you don't need to re-invent the wheel and you can take an existing library instead so you can better concentrate on the actual work that needs to be done in your application.

    0 讨论(0)
  • 2021-01-18 07:51

    Create a function that creates the connection on demand and provides access to the connection object:

    function getDb()
    {
        static $db;
        if (!$db) $db = ...;
        return $db;
    }
    

    Wrapped into class this approach is called Singleton

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题