aplia / support
提供额外支持类和函数,以便更容易地使用PHP
Requires
- php: >=5.3
- ext-mbstring: *
- composer/composer: >=1.0
This package is auto-updated.
Last update: 2024-09-24 19:11:42 UTC
README
此包包含额外的支持类和函数,以便更容易地使用PHP。它实现了PHP中缺少但通常需要的某些功能,例如数组和路径操作。
所有类都放置在命名空间 Aplia\Support
下,例如
use Aplia\Support\Arr; Arr::get($array, 'key');
安装
使用Composer安装
composer require aplia/support
Arr
用于处理数组的各种功能。这些功能大多来自Laravel框架,并放置在此存储库中以避免额外的依赖。
Arr::get
use Aplia\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; $price = Arr::get($array, 'products.desk.price'); // 100
一个典型的用例是通过传递数组作为参数来支持函数的关键字参数。然后可以使用 Arr::get
来轻松获取参数(如果已设置)或使用默认值。
use Aplia\Support\Arr; function search($query, $params = null) { $limit = Arr::get($params, 'limit'); $fields = Arr::get($params, 'fields', 1); // ... }
Path
路径操作,例如将多个文件/目录名连接到一个路径。
Path::join(['var', 'storage']); // "var/storage"
Path::join([]); // ""
// Using a root Path::join(['var', 'storage'], '/var/www'); // "/var/www/var/storage"
Path::make('vendor', 'composer'); // "vendor/composer"
LoggerAdapter
将PSR日志接口适配到eZ debug,将其作为处理程序添加到任何PSR日志。如果存在类 eZDebug
,它将传递日志消息。
Val
强制变量为简单值,调用闭包以获取实际值。
use Aplia\Support\Val; // Any regular value is simply returned Val::value(5) === 5; // Closures are called to fetch the actual value Val::value(function () { return 5; }) === 5;
VirtualProperties
自1.1版起可用
一个特性,使得创建具有虚拟属性的类更容易。
虚拟属性是在对象上不存在的属性,但绑定到当在对象上访问属性名称时被调用的函数。这一切都是通过使用PHP的魔法方法 __get()
、__isset()
、__set()
和 __unset()
来实现的。
如果类扩展了基类,并且该类也实现了 __isset()
等,VirtualProperties 将确保它们在检查过程中被调用。
如果存在 __baseProperties()
,它将在调用 __properties()
时使用此来添加额外的属性。
默认情况下,属性查找是严格的,并在 __get()
中抛出 PropertyError
以处理缺失的属性,要禁用严格性,重新实现方法 __requireProperties()
并使其返回 false
。
使用所有功能的类示例,它将具有以下属性
- name - 正常
- id - 虚拟且只读
- version - 虚拟
- code - 虚拟且缓存
/** * @property-read string $id * @property string $version * @property string $code *\/ class Topic { use \Aplia\Support\Traits\VirtualProperties; public $name; protected $_id; protected $_version; public function __construct($id, $version, $name) { $this->_id = $id; $this->_version = $version; $this->name = $name; } public function cachedCode() { return $this->version !== null ? ($this->_id . '-' . $this->version) : $this->_id; } public function propId($id) { return $this->_id; } public function propVersion() { return $this->_version; } public function setpropVersion($version) { $this->_version = $version; } public function unsetpropVersion() { $this->_version = null; } } $t = new Topic('english', '1', 'foo'); $t->name; // returns 'foo' (regular property) $t->id; // returns 'english' $t->id = 'greek'; // *id* is read-only so this fails $t->version; // returns '1' $t->code; // returns 'english-1' $t->version = '2'; $t->code; // returns 'english-2' unset($t->version); $t->code; // returns 'english'
TemplateAttributes
自1.1版起可用
一个特性,为类提供了对eZ publish模板属性的支持。
使用此特性,类将允许实例在eZ publish模板中使用。属性将映射到类上的现有属性或虚拟属性。
与 VirtualPropertes
结合使用时效果最佳。
许可证
辅助库是开源软件,许可协议为MIT。