Interested in specific cases. For a DB and separate classes. How to create it, I understood, and where to apply it is not. In what cases do I need a single connection to the database and one instance of the object?

    1 answer 1

    For example, to access the session object. Well, or to access the same mysql connection, which is indicated in the tags. It turns out something like:

    Db::Connection()->query("SHOW TABLES"); 

    This approach is usually used in any ORMs, in order not to create 100,500 connections to a single database.

    When working with sessions, it is convenient to check whether the user from whom the request came from is authorized or not)

     Session::instance()->isAuthorized(); // true if authorized, else false. 

    These are examples of possible bikes.

    In Yii, for example, the singleton is the application itself (accessible via Yii::app() ).

    In short, a singleton should make those objects that in your application should have only 1 instance.

    • By the way, a bad idea to parallel the connection to the database? For example simple-fast requests are planned, and one long one that can be executed separately for some time, asynchronously. - Sergiks
    • thanks nolka - zloctb
    • If my answer satisfied you, mark it as correct (click the checkbox left) - nolka
    • 2
      @sergiks - you can hide the connection pool logic inside your singleton - Zowie