Design Patterns: How to create database object/connection only when needed?

前端 未结 10 1000
野的像风
野的像风 2020-11-29 21:04

I\'ve a simple application, say it has some classes and an \"extra\" one that handles database requests. Currently i\'m creating the database object everytime the app is use

10条回答
  •  误落风尘
    2020-11-29 22:01

    Look into using a dependency injection container, something like Pimple would be nice place to start. With a dependency injection container you 'teach' the container how to create the objects in your application, they're not instantiated until you ask for them. With Pimple, you can configure a resource to be shared so that it's only ever instantiated once during the request no matter how often you ask the container for it.

    You can setup your classes to accept the container in their constructor or use a setter method to inject into your class.

    A simplified example could look like this:

    share(
      function ($c) {
        return new Database();
      }
    );
    
    // somewhere else in your application
    
    $foo = new Foo($container);
    
    // somewhere in the Foo class definition
    
    $bar = $this->container['db']->getBars();
    

    Hope it helps.

提交回复
热议问题