Home >Backend Development >PHP Tutorial >Service Container Bootstrap: Getting Started
Before starting the topic, create two new files in controllers directory:
A Service Container is a design pattern that centralizes the management of dependencies between objects, providing a structured way to access and manage services within an application.
It acts as a registry for services within a website.
Firstly create a file named Controller.php in Core directory. In this initialize the Container class, that is responsible for managing service bindings and resolutions.
class Container { protected $bindings = []; public function bind($key, $resolver) { $this->bindings[$key] = $resolver; } public function resolve($key) { if (!array_key_exists($key, $this->bindings)) { throw new Exception("No matching binding found for {$key}"); } $resolver = $this->bindings[$key]; return call_user_func($resolver); } }
The App class acts as a interface for the Container, providing a convenient interface for accessing services.
class App { protected static $container; public static function setContainer($container) { static::$container = $container; } public static function container() { return static::$container; } public static function bind($key, $resolver) { static::container()->bind($key, $resolver); } public static function resolve($key) { return static::container()->resolve($key); } }
Bootstrap is a point of an application, where everything is set up and initialized.
$container = new Container(); $container->bind('Core\Database', function () { $config = require base_path('config.php'); return new Database($config['database']); }); App::setContainer($container);
In this , the bootstrap process:
Services can be resolved from the container in controllers using the App::resolve() method.
$db = App::resolve('Core\Database');
Now a service container is properly built and you can see the project is working well.
I hope that you have clearly understood it.
The above is the detailed content of Service Container Bootstrap: Getting Started. For more information, please follow other related articles on the PHP Chinese website!