Searching for an elegant way in PHP for loading dependencies/services/configuration?

前端 未结 2 1712
慢半拍i
慢半拍i 2021-01-15 08:54

I\'m building a MVC PHP framework and I wonder which are the best practices to load what I need in my classes, be it other classes or plain configuration.

Till today

2条回答
  •  难免孤独
    2021-01-15 09:10

    Why reinvent the wheel? Use Pimple as your DI container, and learn how to use it from its documentation.

    Or, use Silex microframework as a base to create your own framework. It extends Pimple functionality, so you can use dependency injection.

    To answer your question, this is how you use a DI without coupling your classes to it:

    interface ContainerInterface {
        public function getService($service_name);
        public function registerService($service_name,Closure $service_definition);
    }
    
    class Application {
        public function __construct(ContainerInterface $container) {
            $this->container= $container;
        }
    
        public function run() {
            // very simple to use!
            $this->container->getService('db')->someDatabaseQuery();
        }
    }
    
    $c = new My_DI_Container;
    
    // Service definitions could be in a separate file
    $c->registerService('db',function() { return new Database('some config'); });
    
    // Then you inject your DI container into the objects that need it
    $app = new Application($c);
    $app->run(); // or whatever
    

    This way, the DI container is decoupled and in the future you could use a different implementation. The only requirement is that it implements the ContainerInterface.

    Note that the container object is being pushed, and not pulled. Avoid using singleton. To get/set single-instance objects, use the container (that's its responsibility). And to get the container instance, just push it through constructors.

提交回复
热议问题