dhii / wp-containers
v0.1.0-alpha1
2019-05-10 15:04 UTC
Requires
- php: ^7.0 | ^8.0
- dhii/data-container-interface: ^0.2.1-alpha1
- psr/container: ^1.0
Requires (Dev)
- brain/monkey: ^2
- gmazzap/andrew: ^1.1
- phpunit/phpunit: ^6
- slevomat/coding-standard: ~4.0
This package is auto-updated.
Last update: 2021-02-16 17:29:21 UTC
README
请在 Packagist 上检查替代方案
详细信息
PSR-11 容器实现,封装了一些 WP 功能,以方便互操作性。
功能
通过密钥检索站点
use Dhii\Wp\Containers\Sites; use WP_Site; $sites = new Sites(); $site2 = $sites->get(2); assert($site2 instanceof WP_Site);
通过密钥检索站点选项
use Dhii\Wp\Containers\Options\BlogOptions; use Dhii\Wp\Containers\Options\BlogOptionsContainer; use Dhii\Wp\Containers\Sites; // Set up sites container (see other example) // ... assert($sites instanceof WP_Site); // 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 Dhii\Wp\Containers\Options\SiteMeta; use Dhii\Wp\Containers\Options\SiteMetaContainer; use Dhii\Wp\Containers\Sites; // Set up sites container (see other example) // ... assert($sites instanceof WP_Site); // 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 Dhii\Wp\Containers\Options\BlogOptions; use Psr\Container\NotFoundExceptionInterface; use Psr\Container\ContainerExceptionInterface; use Dhii\Data\Container\Exception\NotFoundExceptionInterface as ExtendedNotFoundException; // 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 ExtendedNotFoundException); echo sprintf('Option "%1$s" does not exist', $e->getDataKey()); assert($e->getContainer() === $options); }
这解决了原生 WordPress 选项相关函数行为不一致的问题
- 检索到的选项在值为
false
和未找到时都返回false
,使得它们难以区分; - 设置选项在失败和值与当前值相同时都返回
false
,通常导致错误。
上面的容器不再是这样了:选项操作成功或正确失败会抛出 PSR-11 异常。此外,这些异常的原生行为已经扩展,允许检索未找到的密钥(如果适用)和失败操作的容器。然而,这通常是可选的,并且仅依赖于 PSR-11 异常将按预期工作。
set()
、has()
和 delete()
在失败时也会抛出 ContainerExceptionInterface
。
封装 WP
容器不会重新创建绕过 WordPress 的功能。相反,它们封装原生 WordPress 功能,因此您可以确信所有操作都是以相同的方式进行,所有的钩子,如 option_*
或 pre_update_option_*
,仍然正常工作。