underdev / utils
此包的最新版本(1.1.3)没有可用的许可信息。
WordPress 工具
1.1.3
2018-10-24 07:03 UTC
Requires
- php: >=5.3.9
This package is auto-updated.
Last update: 2024-09-14 00:50:11 UTC
README
WordPress 工具类,用于插件开发
使用示例
首先包含 Composer 的自动加载器。
require_once( 'vendor/autoload.php' );
单例
use underDEV\Utils\Singleton; class Example extends Singleton {} Example::get();
AJAX
AJAX 请求的辅助类。
use underDEV\Utils\Ajax; function ajax_callback() { $ajax = new Ajax(); // verify nonce // you can pass the $_REQUEST array key for nonce as the second argument $ajax->verify_nonce( 'key_for_nonce' ); // do stuff // ... // send output // if errors array will not be empty, it's considered as an error respose $ajax->response( $success = 'success message', $errors = array() ); }
文件
插件文件的辅助类。
use underDEV\Utils\Files; // argument should be the main plugin file $files = new Files( __FILE__ ); // get asset url // will return: your-plugin/assets/dist/css/style.css $files->asset_url( 'css', 'style.css' ) // get vendor asset url // will return: your-plugin/assets/vendor/vendor_name/asset.css $files->vendor_asset_url( 'vendor_name', 'asset.css' )
请查看类的源代码以了解所有方法。
视图
加载视图的辅助类。使用文件类。
use underDEV\Utils\Files; use underDEV\Utils\View; // argument should be the main plugin file $files = new Files( __FILE__ ); $view = new View( $files ); // set some view var $view->set_var( 'var_name', 'value' ); // load view // this will load ./views/parts/menu.php $view->get_view( 'parts/menu' );
在模板文件中可以获取变量
<div><?php echo $this->get_var( 'var_name' ); ?></div>
要在模板中拥有不同的作用域,必须实例化不同的类。
缓存
缓存接口。有两个实现
- 对象缓存 - 如果 WordPress 缓存未设置,则不会持久化
- 瞬态缓存
基本用法
use underDEV\Utils\Cache\ObjectCache; use underDEV\Utils\Cache\Transient; // create new cache object giving it a key and group $cached_object = new ObjectCache( 'object_key', 'object_group' ); var_dump( $cached_object->get() ); // inspect cached value // create new transient cache giving it a key and expiration in seconds $transient_cache = new Transient( 'transient_key', 3600 ); var_dump( $transient_cache->get() ); // inspect cached value
将缓存的元素注入到类中
use underDEV\Utils\Interfaces\Cacheable; use underDEV\Utils\Cache\ObjectCache; use underDEV\Utils\Cache\Transient; class MyClass { /** * Cached object * @var mixed */ protected $cached_element; /** * Constructor * @param Cacheable $cached_element */ public function __construct( Cacheable $cached_element ) { $this->cached_element = $cached_element; } public function inspect_element() { var_dump( $this->cached_element->get() ); } } $myclass = new MyClass( new ObjectCache( 'object_key', 'object_group' ) ); $myclass->inspect_element(); // dumps object cached variable // you can substitute MyClass constructor argument with // any object of class that implements Cacheable $myclass = new MyClass( new Transient( 'transient_key', 3600 ) ); $myclass->inspect_element(); // dumps cached transient variable
查看 Cacheable 接口以获取所有可用方法。
Dice
依赖注入容器。从 Tom Butler 的 Dice 库分支而来。兼容 PHP 5.4