jhonymiler / di
v1.0.0
2023-07-23 06:16 UTC
Requires (Dev)
- larapack/dd: ^1.1
- pestphp/pest: ^2.9
This package is auto-updated.
Last update: 2024-09-23 08:46:29 UTC
README
容器使用文档
容器使用文档
容器类是一个基本的依赖注入容器,允许你在应用程序中管理依赖关系并自动解决它们。它提供了一种方便的方式来处理对象实例化和依赖注入,使你的代码更加模块化和易于维护。
入门
要开始使用Container类,你首先需要包含相关的PHP文件并创建容器的一个实例
use Tests\Core\Container; require 'vendor/autoload.php'; $container = Container::getInstance();
将类绑定到容器
你可以使用bind
方法将类或闭包绑定到容器。当你从容器请求一个实例时,它将自动为你解决绑定的依赖关系。
// Binding a customized MysqlDb instance to the container $container->bind(MysqlDb::class, function () { // Custom configuration for MysqlDb, if needed $db = new Db(/*...*/); return new MysqlDb($db); });
解决依赖
当你用类名调用get
方法时,容器将解决并返回该类的一个实例,以及它的依赖。
// Retrieving an instance of MysqlDb from the container $mysqlDb = $container->get(MysqlDb::class); // Retrieving an instance of User from the container $user = $container->get(User::class);
依赖注入
当使用call
方法时,容器可以自动将依赖注入到闭包中。这允许你为特定的函数或方法解决依赖关系。
// Using the call method to automatically resolve dependencies for a closure $container->call(function (Logger $logger, EntityManager $em) use ($user) { // Here, the logUserData method of the User class will be called with resolved dependencies $user->logUserData($logger); $data = $em->getData(); var_dump($data); });
错误处理
如果容器中找不到类,或者有未解决的依赖,Container类将抛出一个Exception
。在你的应用程序中正确处理这些异常是很重要的,以确保平稳运行。
try { $invalidInstance = $container->get(NonExistentClass::class); } catch (Exception $e) { // Handle the exception here }
结论
Container类简化了PHP应用程序中依赖关系的管理。通过绑定类和闭包,你可以轻松解决具有依赖关系的实例,使你的代码更加有序且易于维护。