zorac/php-di-migration

简化从PHP-DI 6注解到PHP-DI 7属性的迁移

1.0.0 2023-04-20 10:35 UTC

This package is auto-updated.

Last update: 2024-09-20 13:54:42 UTC


README

Software license PHP version Latest release

简化从PHP-DI 6注解到PHP-DI 7属性的迁移。

原因

PHP-DI 7用原生的PHP 8 #[Inject]#[Injectable] 属性替换了PHPDoc @Inject@Injectable 注解。这是一个非常好的变化,但需要一次性更新所有代码,这在拥有多个贡献者的庞大代码库中可能很困难或危险。该项目通过在迁移代码的同时支持属性和注解,提供了一个更平滑的迁移路径。

警告

此代码未对所有用例和边缘情况进行广泛测试。使用风险自负!

用法

与PHP-DI 6一起安装迁移包

composer require zorac/php-di-migration

ContainerBuilder 替换为 MigrationContainerBuilder 并启用注解

// Before:
$builder = new DI\ContainerBuilder();
$builder->useAnnotations(true);
// etc...
$container = $builder->build();

// After:
$builder = new DI\MigrationContainerBuilder();
$builder->useAnnotations(true);
$builder->useAttributes(true);
// etc...
$container = $builder->build();

提交并合并更改,然后您可以开始迁移!

随着时间的推移,将您的代码从属性迁移到注解,记得在当前依赖PHPDoc类型的任何地方添加强PHP类型,并删除任何 DI\Annotation\Inject 等导入。

一旦您的代码全部迁移完成,从容器构建器中删除 useAnnotations(false) 调用进行最终测试。如果您错过了任何类型更改,此时会出现问题。

一旦您对完全迁移的代码满意,您可以删除 zorac/php-di-migration 并升级到PHP-DI 7,切换回使用 DI\ContainerBuilder。如果您没有其他用途,也可能删除 doctrine/annotations

恭喜!您的PHP-DI迁移已完成。

实现说明

  • MigrationContainerBuilder 是PHP-DI 6的 ContainerBuilder 的修改版,其中包含从PHP-DI 7版本移植的更改,以添加对 useAttributes 的支持,以及对并行支持注解和属性的其他更改。
  • AttributeAndAnnotationBasedAutowiring 是PHP-DI 6的 AnnotationBasedAutowiring 的修改版,其中包含从PHP-DI 7的 AttributeBasedAutowiring 移植的更改,以支持并行注解和属性。
  • 所有其他类都是直接从PHP-DI 7复制的。