当前位置:首页 > PHP

php实现容器

2026-03-12 22:16:53PHP

PHP 实现容器的方法

在 PHP 中,容器通常用于依赖注入(DI)和管理对象生命周期。以下是几种常见的实现方式:

使用 PSR-11 兼容容器

PHP-FIG 的 PSR-11 标准定义了容器接口,可以通过实现 Psr\Container\ContainerInterface 来创建标准容器:

use Psr\Container\ContainerInterface;

class Container implements ContainerInterface {
    private $services = [];

    public function get($id) {
        if (!$this->has($id)) {
            throw new NotFoundException("Service not found: {$id}");
        }
        return $this->services[$id];
    }

    public function has($id) {
        return isset($this->services[$id]);
    }

    public function set($id, $service) {
        $this->services[$id] = $service;
    }
}

依赖注入容器实现

更高级的容器可以支持自动依赖解析:

class DIContainer {
    private $definitions = [];
    private $instances = [];

    public function set($id, $definition) {
        $this->definitions[$id] = $definition;
    }

    public function get($id) {
        if (isset($this->instances[$id])) {
            return $this->instances[$id];
        }

        if (!isset($this->definitions[$id])) {
            throw new Exception("Service not defined: {$id}");
        }

        $definition = $this->definitions[$id];
        $instance = $this->resolve($definition);
        $this->instances[$id] = $instance;

        return $instance;
    }

    protected function resolve($definition) {
        if (is_callable($definition)) {
            return $definition($this);
        }

        if (is_string($definition) && class_exists($definition)) {
            $reflection = new ReflectionClass($definition);
            $constructor = $reflection->getConstructor();

            if (!$constructor) {
                return new $definition();
            }

            $parameters = $constructor->getParameters();
            $dependencies = [];

            foreach ($parameters as $parameter) {
                $type = $parameter->getType();
                if ($type && !$type->isBuiltin()) {
                    $dependencies[] = $this->get($type->getName());
                } else {
                    throw new Exception("Cannot resolve parameter: {$parameter->getName()}");
                }
            }

            return $reflection->newInstanceArgs($dependencies);
        }

        return $definition;
    }
}

使用现有容器库

PHP 生态系统中有多个成熟的容器实现:

php实现容器

  1. PHP-DI: 功能丰富的依赖注入容器

    $container = new DI\Container();
  2. Symfony DependencyInjection: Symfony 框架的组件

    php实现容器

    $container = new Symfony\Component\DependencyInjection\ContainerBuilder();
  3. Laravel 容器: Laravel 框架的核心组件

    $container = new Illuminate\Container\Container();

容器配置示例

典型的容器配置和使用方式:

$container = new DIContainer();

// 注册服务
$container->set('database', function($c) {
    return new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
});

$container->set('user_repository', 'App\Repositories\UserRepository');

// 获取服务
$db = $container->get('database');
$userRepo = $container->get('user_repository');

容器的高级特性

成熟的容器通常支持以下特性:

  • 自动装配(Autowiring)
  • 服务标签(Service Tags)
  • 工厂方法(Factories)
  • 延迟加载(Lazy Loading)
  • 作用域管理(Scopes)
  • 参数注入(Parameter Injection)

选择容器实现时,应根据项目需求和复杂度决定是自行实现还是使用现有解决方案。对于大多数应用场景,成熟的容器库如 PHP-DI 或 Symfony DI 已经足够完善。

标签: 容器php
分享给朋友:

相关文章

php实现打印功能

php实现打印功能

PHP 实现打印功能的方法 PHP 可以通过多种方式实现打印功能,具体取决于打印的目标(如打印机、PDF、网页等)和需求(如直接打印、生成打印预览等)。以下是几种常见的实现方式: 使用 JavaSc…

php实现websocket

php实现websocket

PHP 实现 WebSocket WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议。PHP 可以通过多种方式实现 WebSocket 功能,以下是几种常见的方法: 使用 Ratc…

php实现登录

php实现登录

PHP 登录功能实现 数据库连接与用户表创建 创建一个数据库连接文件 db.php,用于管理数据库连接。MySQL 示例代码如下: <?php $host = 'localhost'; $db…

php搜索功能实现

php搜索功能实现

实现基本的PHP搜索功能 使用MySQL数据库和PHP实现简单的关键词搜索功能。需要确保数据库中有可供搜索的表和数据。 // 连接数据库 $conn = new mysqli('localhost'…

php 实现单链表

php 实现单链表

单链表的基本概念 单链表是一种线性数据结构,由节点组成,每个节点包含数据域和指向下一个节点的指针域。链表的头节点是访问整个链表的入口。 单链表的节点类实现 在PHP中,可以通过类来定义链表节点。每个…

php实现mvc

php实现mvc

PHP 实现 MVC 架构 MVC(Model-View-Controller)是一种常用的软件设计模式,将应用程序分为三个核心组件:模型(Model)、视图(View)和控制器(Controller…