Loading video...

< Decorator (Explanation) >

Decorator explanation.

Design Patterns in PHP to Solve real-life Software Problems
Comment section
  • Renato Hysa
    Software Engineer
    11 months ago

    Even for a Database connection class, you are not supposed to use the singleton design pattern.

    Languages such as Java, use a connection pool. A connection pool is an implementation of the pool design pattern that is already explained in this course.

    In PHP that is not possible. The reason why is because once a PHP file has finished execution, then the state is destroyed. I am aware of mysql-pconnect, but I have never used it to tell you for sure if that fixes this problem.

    Laravel uses the factory design pattern to CREATE a database connection.

    Inside config/app.php you define all the service providers that your application requires to work properly, one of them is DatabaseServiceProvider


    Inside that class, there is a register() method go there and then take a look at the code inside this method registerConnectionServices() .

    $this->app->singleton('db', function ($app) {
        return new DatabaseManager($app, $app['db.factory']);

    It passes a factory to the DatabaseManager class.

    Inside DatabaseManager you have a connection() method. That method calls this protected method makeConnection() . makeConnection() uses the factory design pattern to create a new connection.

    A Database class is a very complex object.

    You just have to remember that Singleton is bad. It has its place, but 99.9% of the times it should be avoided.

    Frameworks are very complex. I have been working on my own PHP framework for some time now. I hope I can finish it this year and publish it on GitHub.

    1 0
  • Alberto Gomis
    Wannabe Dev
    11 months ago

    I'm a little confused now. If the Singleton and Registery are bad patterns and cannot in any way support a reset function then what are the alternatives for situations when you do need an single instance of a class. In the case of a database connector class for example. What would be the approach to having a single instance of that database connector class without a singleton?

    1 0