rmp-up / wp-di
简单的依赖注入/服务容器,用于WordPress中更多面向对象编程(PSR-11兼容)
0.8.0
2021-01-16 15:26 UTC
Requires
- pimple/pimple: ^3.0
Requires (Dev)
- php: 7.0 - 7.4 || 8.0.*
- bamarni/composer-bin-plugin: ^1.4
- johnpbloch/wordpress: 5.2.*
- perftools/php-profiler: 0.12.*
Suggests
- symfony/yaml: To maintain services the most common way
Conflicts
- symfony/yaml: <3.4
README
WP DI
基于Pimple的WordPress PHP依赖注入
这并不是什么新东西,但我们增加了一些魔法
- 兼容已使用Pimple的项目
- 通过纯数组、Yaml或其他方式配置
- "更少WordPress,更多OOP"
并且仍在寻找其他魔法来应用。
入门
将包添加到您的项目中
composer require rmp-up/wp-di
并设置容器提供者
RmpUp\WpDi\WpDi::load( require 'services.php' ); $container = \RmpUp\WpDi\WpDi::pimple();
YAML的爱好者可以添加 composer require symfony/yaml
并使用
RmpUp\WpDi\WpDi::load( RmpUp\WpDi\Yaml::parseFile( 'services.yaml' ) );
功能
完整文档可以在最新发布版本的文档中找到。以下只是对一些可能性的预览。当您有PHP >= 7.4或Composer工作流时,尝试使用“preload.php”以获得更好的性能
{ "autoload": { "files": [ "vendor/rmp-up/wp-di/preload.php" ] } }
服务和参数
定义服务,就像从经典的DI中已知的那样,但也...
- 原始参数如常
- 选项的默认值
- 模板路径
- 将这些全部注入到服务中
- 允许工厂创建服务
# Primitive parameters as usual parameters: some: "primitives" like: 42 # Default values for options options: _my_plugin_rating: 5/7 _this_is: cool # Path to templates templates: admin-view: my-own-plugin/template-parts/fester.php frontend-view: my-own-plugin/public/coogan.jpg # looks up the file in theme, theme-compat and plugin directory # Inject all of them into services services: SimpleOne: arguments: - "Hello there!" - 1337 SomeThing: arguments: - "%like%" # the parameter - "%_this_is%" # the option - "%frontend-view%" # path to the template - "@SimpleOne" # the other service
在WordPress中注册服务
服务也可以用于...
- 添加操作/过滤器
- 添加元框
- 注册文章类型
- 注册短代码
- 注册小工具
- 添加WP-CLI命令
services: StrrevEverything: filter: the_content # calling `::__invoke` for the "the_content"-filter BackendAdminListThing: meta_box: title: Greatest box in the World! screen: post MyOwnPostType: post_type: animals # cast service to array and forward to register_post_type BestShortcodeEver: shortcode: shortcode_wont_die widget: ~ # Shortcode and widget at once. Wow! DoItCommand: wp_cli: do-it: __invoke doit: __invoke seriously do-it do-it do-it: seriously # cli commands mapped to methods
使用标签来增强Yaml
在Yaml中,您可以
- 访问PHP-常量
- 连接文本
- 翻译文本
主要为了获得最佳性能而尽量懒散。
services: # Access PHP-Constants InjectingConstants: arguments: - !php/const ABSPATH # Concatenate text ThisIsSomeTemplate: arguments: - !join [ !php/const WP_CONTENT_DIR, "/plugins/grey-matter/walter.jpg" ] # Translations within YAML ThisThingNeedsTranslations: arguments: - !__ [ Who is Adam?, dark ] - !esc_attr__ [ white ] # ... many more translation functions available ...
所有这些都只有在使用 \RmpUp\WpDi\Yaml::parseFile(...)
或 ::parse(...)
时才可能。
贡献
我们在一些项目中使用了这个,并且仍在维护/增强它,所以如果有什么我们可以帮助的,请提出问题。
如果您想贡献,请将仓库分叉,并按您喜欢的任何方式修改。欢迎提交拉取请求。
相关项目
请注意以下关于WordPress中依赖注入容器的项目
许可
有关详细信息,请参阅LICENSE.txt。