Pimple 是一个用于 PHP 的简单依赖注入容器。要使用 Pimple 实现依赖注入,请按照以下步骤操作:
安装 Pimple:首先,你需要通过 Composer 安装 Pimple。在你的项目根目录中运行以下命令:composer require pimple/pimple创建 Pimple 容器:在你的项目中创建一个新的 PHP 文件(例如 container.php),并引入 Pimple 库。然后,创建一个新的 Pimple 容器实例:<?phprequire 'vendor/autoload.php';use Pimple\Container;$container = new Container();定义服务和依赖关系:使用 Pimple 容器,你可以定义服务和它们的依赖关系。例如,假设你有一个 Database 类和一个 UserRepository 类,你可以这样定义它们:<?php// ...class Database{ // ...}class UserRepository{ private $database; public function __construct(Database $database) { $this->database = $database; } // ...}$container['database'] = function ($c) { return new Database();};$container['user_repository'] = function ($c) { return new UserRepository($c['database']);};使用服务:现在,你可以在你的应用程序中使用这些服务。例如,你可以在一个控制器中使用 UserRepository:<?php// ...class UserController{ private $userRepository; public function __construct(UserRepository $userRepository) { $this->userRepository = $userRepository; } // ...}$userController = new UserController($container['user_repository']);这就是如何使用 Pimple 实现依赖注入的基本方法。通过这种方式,你可以更好地组织和管理你的代码,使其更易于测试和维护。


