wp-oop / containers
PSR-11 容器实现,包装了一些 WP 功能,以方便和互操作性。
v0.1.1-alpha3
2023-09-21 00:22 UTC
Requires
- php: ^7.1 | ^8.0
- dhii/collections-interface: ^0.3.0-alpha1
- psr/container: ^1.0
Requires (Dev)
- brain/monkey: ^2.0
- gmazzap/andrew: ^1.1
- johnpbloch/wordpress-core: ^5.0
- php-stubs/wordpress-stubs: ^5.0
- phpunit/phpunit: ^6.0 | ^7.0 | ^8.0 | ^9.0
- slevomat/coding-standard: ^4.0 | ^5.0 | ^6.0
- vimeo/psalm: ^3.11.7 | ^4.0
Conflicts
- vimeo/psalm: 4.5.1 || 4.5.0
This package is auto-updated.
Last update: 2024-09-21 02:20:19 UTC
README
详情
PSR-11 容器实现,包装了一些 WP 功能,以方便和互操作性。PSR-11
特性
通过键检索站点
use WpOop\Containers\Sites; use WP_Site; $sites = new Sites(); $site2 = $sites->get('2'); assert($site2 instanceof WP_Site);
通过键检索站点选项
use WpOop\Containers\Options\BlogOptions; use WpOop\Containers\Options\BlogOptionsContainer; use WpOop\Containers\Sites; // Set up sites container (see other example) // ... assert($sites instanceof Sites); // Definition $optionsContainer = new BlogOptionsContainer( function ($id) { return new BlogOptions($id, uniqid('default-option-value')); }, $sites ); // Usage $blog3Options = $optionsContainer->get('3'); $myOption = $blog3Options->get('my_option');
通过键检索站点元数据
use WpOop\Containers\Options\SiteMeta; use WpOop\Containers\Options\SiteMetaContainer; use WpOop\Containers\Sites; // Set up sites container (see other example) // ... assert($sites instanceof Sites); // Definition $metaContainer = new SiteMetaContainer( function ($id) { return new SiteMeta($id, uniqid('default-meta-value')); }, $sites ); // Usage $blog4Meta = $metaContainer->get('4'); $myMeta = $blog4Meta->get('my_meta');
结构化错误处理
use WpOop\Containers\Options\BlogOptions; use Psr\Container\NotFoundExceptionInterface; use WpOop\Containers\Exception\NotFoundException; // Set up options (see previous examples) // ... assert($options instanceof BlogOptions); try { $options->set('other_option', 'My Value'); $value = $options->get('my_option'); } catch (NotFoundExceptionInterface $e) { assert($e instanceof NotFoundException); echo sprintf('Option "%1$s" does not exist', $e->getDataKey()); assert($e->getContainer() === $options); }
这解决了原生 WordPress 选项相关函数行为不一致的问题
- 检索到的选项返回
false
,无论是值为false
还是未找到,使得它们难以区分; - 设置选项返回
false
,无论是失败还是值与当前值相同,通常会导致错误。
使用上述容器后,这种情况不再存在:选项操作通过抛出 PSR-11 异常来成功或正确失败。此外,这些异常的原始行为已扩展到允许检索未找到的键(如果适用)以及失败操作的容器。这虽然是可选的,但仅依赖于 PSR-11 异常将按预期工作。
当失败时,set()
、has()
和 unset()
也会抛出 ContainerExceptionInterface
。
包装 WP
这些容器并不重新创建绕过 WordPress 的功能。相反,它们包装原生 WordPress 功能,因此您可以确信一切都是以相同的方式进行,所有的钩子,如 option_*
或 pre_update_option_*
,仍然工作。