If the database connection class in itself has the query function and at the end has the connection closed, does it make sense in this situation to make Singleton out of it? And is it even correct to implement a connection, request and closing connection in one class? As an option, perhaps, close () to display a separate function and call as needed, rather than close the connection every time after each request?

  • one
    @ - A Singleton not needed. At all. Fair. One copy is needed - use one copy, store in the registry or container. > And is it even correct to implement the connection, query and close connection in one class? Yes. Your class implies a single database connection. You need to open it, close it, drop a ton of requests into it and get a ton of answers from it. > As an option, perhaps close () to a separate function and call as needed, and not close the connection each time after each request? Not that it is possible, necessarily. - etki
  • Clear answer, thanks. When the page loads, different modules are connected that access the same database each with their own requests and it turns out that several copies of the database connection class are created. Hence, the questions are to close the connection immediately after each (!) Request or close at the end of the script execution, so that everyone can complete the requests (equivalent to not closing at all, since everything ends at the end of the script execution) or the option to implement Singleton and give one single copy to all? I did not come across registries and containers. Can be more in detail, please - --A
  • "store in the registry" - the registry is a special case of a singleton so then - drch

1 answer 1

There is no need to use a singleton for connecting to the database:

  1. At the level of the driver that establishes communication with the DBMS, the connection is not re-established if there is already a connection with the same parameters. Instead, an existing connection is returned.
  2. It makes sense to close the connection if you expect a slow request that will be processed by PHP for some reason. For example, they made a request to the database and began to give the user a 4GB file. A busy connection will not participate in the processing of other requests and if there are no more connections expected in the current script, it makes sense to close the connection to the database before the user begins to download volumetric data for a long time. If your script takes several microseconds, there is no need to explicitly close the connections - they will be automatically closed after the script is executed.