0

0

如何解决PHP依赖注入和服务管理的复杂问题?使用ghostwriter/container可以!

WBOY

WBOY

发布时间:2025-05-18 14:20:25

|

387人浏览过

|

来源于php中文网

原创

可以通过一下地址学习composer学习地址

在开发一个大型php项目时,我遇到了一个棘手的问题:如何有效地管理服务依赖和生命周期。随着项目的扩展,服务之间的依赖关系变得越来越复杂,手动管理这些依赖不仅耗时,而且容易出错。我尝试了几种方法,但都没有找到一个既灵活又高效的解决方案。最终,我通过使用ghostwriter/container库成功解决了这个问题。

使用Composer安装ghostwriter/container非常简单:

composer require ghostwriter/container

这个库提供了一个可扩展的依赖注入服务容器,支持自动化的对象组合、拦截和生命周期管理。它通过一系列强大的功能帮助你简化服务管理:

简单使用

你可以轻松地在容器中注册服务:

final readonly class Service
{
    public function __construct(
        private Dependency $dependency
    ) {}

    public function dependency(): Dependency
    {
        return $this->dependency;
    }
}

$container = Container::getInstance();
$service = $container->get(Service::class);

assert($service instanceof Service); // true
assert($service->dependency() instanceof Dependency); // true

使用属性注解

你还可以使用属性注解来注册服务,这使得代码更加清晰和易于维护:

立即学习PHP免费学习笔记(深入)”;

可赞AI
可赞AI

文字一秒可视化,免费AI办公神器

下载

#[Inject]

use Ghostwriter\Container\Attribute\Inject;

final readonly class Service
{
    public function __invoke(
        #[Inject(Dependency::class)]
        DependencyInterface $dependency
    ): Dependency
    {
        return $this->dependency;
    }
}

#[Factory]

use Ghostwriter\Container\Attribute\Factory;

#[Factory(ServiceFactory::class)]
final readonly class Service
{
    public function __construct(
        private Dependency $dependency
    ) {}

    public function dependency(): Dependency
    {
        return $this->dependency;
    }
}

#[Extension]

use Ghostwriter\Container\Attribute\Extension;

#[Extension(ServiceExtension::class)]
final readonly class Service
{
    public function __construct(
        private Dependency $dependency
    ) {}

    public function dependency(): Dependency
    {
        return $this->dependency;
    }
}

#[Provider]

use Ghostwriter\Container\Attribute\Provider;

#[Provider(ServiceProvider::class)]
final readonly class Service
{
    public function __construct(
        private DependencyInterface $dependency
    ) {}

    public function dependency(): DependencyInterface
    {
        return $this->dependency;
    }
}

服务提供者

通过服务提供者,你可以更灵活地管理服务:

interface TaskInterface {}

final readonly class Task implements TaskInterface {}

final class Tasks
{
    private array $tasks = [];
    public function addTask(TaskInterface $task)
    {
        $this->tasks[] = $task;
    }
}

final readonly class TasksServiceProvider implements ServiceProviderInterface
{
    public function __invoke(ContainerInterface $container)
    {
        $container->alias(Task::class, TaskInterface::class);

        // "set" the service instance
        $container->set(FirstTask::class, new FirstTask(), [Task::class]);

        // "define" the service builder
        $container->define(Tasks::class, static function (Container $container) {
            /** @var Tasks $tasks */
            $tasks = $container->build(Tasks::class);

            foreach ($container->tagged(Task::class) as $service) {
                $tasks->addTask($service);
            }

            return $tasks;
        }, [Tasks::class, 'tasks']);

    }
}

$container->provide(TasksServiceProvider::class);

$service = $container->get(TaskInterface::class);

assert($service instanceof Task); // true

上下文绑定

上下文绑定允许你根据不同的上下文注入不同的依赖:

interface ClientInterface {}

final readonly class RestClient implements ClientInterface {}

final readonly class GraphQLClient implements ClientInterface {}

final readonly class GitHub
{
    public function __construct(
        private ClientInterface $client
    ) {
    }
    public function getClient(): ClientInterface
    {
        return $this->client;
    }
}

// When GitHub::class asks for ClientInterface::class, it would receive an instance of GraphQLClient::class.
$container->bind(GitHub::class, ClientInterface::class, GraphQLClient::class);

// When any other service asks for ClientInterface::class, it would receive an instance of RestClient::class.
$container->alias(ClientInterface::class, RestClient::class);

服务扩展

你可以使用服务扩展来增强现有服务的功能:

/**
 * @implements ExtensionInterface
 */
final readonly class GitHubExtension implements ExtensionInterface
{
    /**
     * @param GitHubClient $service
     * @return GitHubClient
     */
    public function __invoke(ContainerInterface $container, object $service): object
    {
        $service->setEnterpriseUrl(
            $container->get(GitHubClient::GITHUB_HOST)
        );

        return $service;
    }
}

$container->alias(GitHubClientInterface::class, GitHubClient::class);
$container->extend(GitHubClientInterface::class, $container->get(GitHubExtension::class));

服务工厂

服务工厂允许你动态创建服务实例:

final readonly class Dependency {}
final readonly class Service
{
    public function __construct(
        private Dependency $dependency
    ){}

    public function dependency(): Dependency
    {
        return $this->dependency;
    }
}
final readonly class ServiceFactory {
  public function __invoke(Container $container): Service
  {
     return new Service($container->get(Dependency::class));
  }
}

$container = Container::getInstance();

$container->factory(Service::class, ServiceFactory::class);

$service = $container->get(Service::class);

assert($service instanceof Service); // true
assert($service->dependency() instanceof Dependency); // true

使用ghostwriter/container库,我能够更加灵活和高效地管理服务依赖和生命周期。它不仅简化了代码,还提高了项目的可维护性和可扩展性。如果你在处理PHP项目中的依赖注入和服务管理问题,强烈推荐你尝试这个库。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
php文件怎么打开
php文件怎么打开

打开php文件步骤:1、选择文本编辑器;2、在选择的文本编辑器中,创建一个新的文件,并将其保存为.php文件;3、在创建的PHP文件中,编写PHP代码;4、要在本地计算机上运行PHP文件,需要设置一个服务器环境;5、安装服务器环境后,需要将PHP文件放入服务器目录中;6、一旦将PHP文件放入服务器目录中,就可以通过浏览器来运行它。

2911

2023.09.01

php怎么取出数组的前几个元素
php怎么取出数组的前几个元素

取出php数组的前几个元素的方法有使用array_slice()函数、使用array_splice()函数、使用循环遍历、使用array_slice()函数和array_values()函数等。本专题为大家提供php数组相关的文章、下载、课程内容,供大家免费下载体验。

1736

2023.10.11

php反序列化失败怎么办
php反序列化失败怎么办

php反序列化失败的解决办法检查序列化数据。检查类定义、检查错误日志、更新PHP版本和应用安全措施等。本专题为大家提供php反序列化相关的文章、下载、课程内容,供大家免费下载体验。

1567

2023.10.11

php怎么连接mssql数据库
php怎么连接mssql数据库

连接方法:1、通过mssql_系列函数;2、通过sqlsrv_系列函数;3、通过odbc方式连接;4、通过PDO方式;5、通过COM方式连接。想了解php怎么连接mssql数据库的详细内容,可以访问下面的文章。

1120

2023.10.23

php连接mssql数据库的方法
php连接mssql数据库的方法

php连接mssql数据库的方法有使用PHP的MSSQL扩展、使用PDO等。想了解更多php连接mssql数据库相关内容,可以阅读本专题下面的文章。

1566

2023.10.23

html怎么上传
html怎么上传

html通过使用HTML表单、JavaScript和PHP上传。更多关于html的问题详细请看本专题下面的文章。php中文网欢迎大家前来学习。

1297

2023.11.03

PHP出现乱码怎么解决
PHP出现乱码怎么解决

PHP出现乱码可以通过修改PHP文件头部的字符编码设置、检查PHP文件的编码格式、检查数据库连接设置和检查HTML页面的字符编码设置来解决。更多关于php乱码的问题详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1669

2023.11.09

php文件怎么在手机上打开
php文件怎么在手机上打开

php文件在手机上打开需要在手机上搭建一个能够运行php的服务器环境,并将php文件上传到服务器上。再在手机上的浏览器中输入服务器的IP地址或域名,加上php文件的路径,即可打开php文件并查看其内容。更多关于php相关问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1310

2023.11.13

拼多多赚钱的5种方法 拼多多赚钱的5种方法
拼多多赚钱的5种方法 拼多多赚钱的5种方法

在拼多多上赚钱主要可以通过无货源模式一件代发、精细化运营特色店铺、参与官方高流量活动、利用拼团机制社交裂变,以及成为多多进宝推广员这5种方法实现。核心策略在于通过低成本、高效率的供应链管理与营销,利用平台社交电商红利实现盈利。

31

2026.01.26

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
第二十四期_PHP8编程
第二十四期_PHP8编程

共86课时 | 3.4万人学习

成为PHP架构师-自制PHP框架
成为PHP架构师-自制PHP框架

共28课时 | 2.5万人学习

第二十三期_PHP编程
第二十三期_PHP编程

共93课时 | 6.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号