popphp/pop-utils
Composer 安装命令:
composer require popphp/pop-utils
包简介
Pop Utilities Component for Pop PHP Framework
关键字:
README 文档
README
- Overview
- Install
- Array Object
- Collection
- Callable Object
- DateTime Object
- File Helper
- Array Helper
- Number Helper
- UUID Helper
- Helper Functions
Overview
pop-utils is a basic utilities component of the Pop PHP Framework. It comes with
a number of utility and helper classes that can be useful when building applications with Pop.
Install
Install pop-utils using Composer.
composer require popphp/pop-utils
Or, require it in your composer.json file
"require": {
"popphp/pop-utils" : "^2.3.0"
}
Array Object
The Pop\Utils\ArrayObject class implements a number of interfaces to allow it to behave like
array, but with much more functionality built in. With it, you can access the array data within
the object via standard array notation ($ary['item']) or via object notation ($ary->item).
You can iterate over the array object and it is countable. Also you can cast it to an native
array using the toArray() method.
use Pop\Utils\ArrayObject; $arrayObject = new ArrayObject(['foo' => 'bar']); echo $arrayObject->foo; echo $arrayObject['foo']; echo count($arrayObject); foreach ($arrayObject as $key => $value) { echo $key . ': ' . $value; } $array = $arrayObject->toArray();
There are also additional serialize/unserialize methods that allow you to work with the array object as JSON-string or PHP-serialized string
use Pop\Utils\ArrayObject; $arrayObject = ArrayObject::createFromJson('{"foo":"bar"}'); echo $arrayObject->jsonSerialize(JSON_PRETTY_PRINT);
use Pop\Utils\ArrayObject; $arrayObject = ArrayObject::createFromSerialized('a:1:{s:3:"foo";s:3:"bar";}'); echo $arrayObject->serialize();
Collection
The collection object is a array-like object with a tremendous amount of array-like functionality built into it. This allows you to call any number of methods on the object to perform operations on the array and its data. It's available API includes:
count(): intfirst(): mixednext(): mixedcurrent(): mixedlast(): mixedkey(): mixedcontains(mixed $key, bool $strict = false): booleach(callable $callback): Collectionevery(int $step, int $offset = 0): Collectionfilter(?callable $callback = null, int $flag = 0): Collectionmap(callable $callback): Collectionflip(): Collectionhas(mixed $key): boolisEmpty(): boolkeys(): Collectioncolumn(string $column): Collectionvalues(): Collectionmerge(mixed $data, $recursive = false): CollectionforPage(int $page, int $perPage): Collectionpop(): mixedpush(mixed $value): Collectionshift(): mixedslice(int $offset, int $length = null): Collectionsplice(int $offset, ?int $length = null, mixed $replacement = []): Collectionsort(?callable $callback = null, int $flags = SORT_REGULAR): CollectionsortByAsc(int $flags = SORT_REGULAR): CollectionsortByDesc(int $flags = SORT_REGULAR): CollectiontoArray(): array
Callable Object
The Pop\Utils\CallableObject class helps to manage callable objects and their parameters.
This includes functions, closures, classes and their methods (both static and instance.)
This is useful for wiring up something that needs to be called or triggered by the application
at a later time.
The parameters can be set anytime in the callable object's life cycle, from the time of instantiation via the constructor, via the set/add methods or at the time of calling the object. Parameters passed into the callable object can be callable themselves and will be invoked at the time the parent callable object is called.
Function Callable
use Pop\Utils\CallableObject; $callable = new CallableObject('trim', ' Hello World!'); echo $callable->call(); // Outputs 'Hello World!'
Closure Callable
use Pop\Utils\CallableObject; $callable = new CallableObject(function ($var) { echo strtoupper($var) . '!';}); $callable->addParameter('hello world'); echo $callable->call(); // Outputs 'HELLO WORLD!'
Here's an alternate way to call by passing the parameter in at the time of the call:
use Pop\Utils\CallableObject; $callable = new CallableObject(function ($var) { echo strtoupper($var) . '!';}); echo $callable->call('hello world'); // Outputs 'HELLO WORLD!'
Static Method Callable
use Pop\Utils\CallableObject; $callable = new CallableObject('MyClass::someMethod'); echo $callable->call(); // Executes the static 'someMethod()' from class 'MyClass'
Instance Method Callable
use Pop\Utils\CallableObject; $callable = new CallableObject('MyClass->someMethod'); echo $callable->call(); // Executes the 'someMethod()' in an instance of 'MyClass'
Constructor Callable
use Pop\Utils\CallableObject; class MyClass { protected $str = null; public function __construct($str) { $this->str = $str; } public function printString() { echo $this->str; } } // Creates an instance of 'MyClass' with the string 'Hello World' passed into the constructor $callable = new CallableObject('MyClass', 'Hello World'); $myInstance = $callable->call(); $myInstance->printString();
DateTime Object
The Pop\Utils\DateTime class extend the native DateTime class and adds some helper functions:
- Add HH:MM:SS formatted times together for a total time in the HH:MM:SS format.
- Average HH:MM:SS formatted times together for an average time in the HH:MM:SS format.
- Get the dates of any week in any year.
use Pop\Utils\DateTime; $times = ['08:45:18', '15:13:58', '09:05:09']; $totalTime = Pop\Utils\DateTime::getTotal($times, '%H:%I:%S'); echo $totalTime . PHP_EOL; // 33:04:25 $averageTime = Pop\Utils\DateTime::getAverage($times, '%H:%I:%S'); echo $averageTime . PHP_EOL; // 11:01:28 $weekDates = DateTime::getWeekDates(40, 2023, 'Y-m-d'); // 40th week of the year 2023 print_r($weekDates); /** Array ( [0] => 2023-10-01 [1] => 2023-10-02 [2] => 2023-10-03 [3] => 2023-10-04 [4] => 2023-10-05 [5] => 2023-10-06 [6] => 2023-10-07 ) */
File Helper
The Pop\Utils\File class get quickly parse and return information about a file,
including the mime type for common file types
use Pop\Utils\File $file = new File(__DIR__ . '/tmp/test.txt'); echo $file->getBasename()); // 'test.txt' echo $file->getFilename()); // 'test' echo $file->getExtension()); // 'txt' echo $file->getMimeType()); // 'text/plain' echo $file->getPath()); // __DIR__ . '/tmp echo $file->getSize()); // 13
You can quickly get just the mime type of a file like this:
use Pop\Utils\File echo File::getFileMimeType(__DIR__ . '/tmp/image.jpg'); // 'image/jpeg'
Array Helper
The Pop\Utils\Arr class has a number of static methods to assist in
manipulating arrays:
Arr::isArray(mixed $value): boolArr::isNumeric(array $array): boolArr::isAssoc(array $array): boolArr::exists(array|ArrayAccess $array, string|int $key): boolArr::key(array|AbstractArray $array, string|int $value, bool $strict = false): mixedArr::collapse(array|AbstractArray $array): arrayArr::flatten(array|AbstractArray $array, int|float $depth = INF): arrayArr::divide(array|AbstractArray $array): arrayArr::slice(array|AbstractArray $array, int $limit, int $offset = 0): arrayArr::split(string $string, string $separator, int $limit = PHP_INT_MAX): arrayArr::join(array|AbstractArray $array, string $glue, string $finalGlue = ''): stringArr::prepend(array|AbstractArray $array, mixed $value, mixed $key = null): arrayArr::pull(array &$array, mixed $key): mixedArr::sort(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $assoc = true, bool $descending = false): arrayArr::sortDesc(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $assoc = true): arrayArr::ksort(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $descending = false): arrayArr::ksortDesc(array|AbstractArray $array, int $flags = SORT_REGULAR): arrayArr::usort(array|AbstractArray $array, mixed $callback, bool $assoc = true): arrayArr::uksort(array|AbstractArray $array, mixed $callback): arrayArr::map(array|AbstractArray $array, mixed $callback): arrayArr::trim(array|AbstractArray $array): arrayArr::filter(array|AbstractArray $array, mixed $callback = null, int $mode = ARRAY_FILTER_USE_BOTH): arrayArr::make(mixed $value): array
String Helper
The Pop\Utils\Str class has a number of static methods to assist in
manipulating and generating strings.
Slugs
use Pop\Utils\Str; echo Str::createSlug('Hello World | Home Page'); // hello-world-home-page
Links
use Pop\Utils\Str; echo Str::createLinks('Test Email test@test.com and Test Website http://www.test.com/');
Test Email <a href="mailto:test@test.com">test@test.com</a> and
Test Website <href="http://www.test.com/">http://www.test.com/</a>
Random Strings
use Pop\Utils\Str; echo Str::createRandom(10); // 5.u9MHw{PC echo Str::createRandomAlpha(10, Str::LOWERCASE); // wvjvvsmnjw echo Str::createRandomAlphaNum(10, Str::UPPERCASE); // 6S73HQ629R echo Str::createRandomAlphaNum(10, Str::MIXEDCASE); // Yfd35M3T92
Convert Case
The convert case feature allows for the following case and string format types:
- TitleCase
- camelCase
- kebab-case (dash)
- snake_case (underscore)
- Name\Space
- folder/path
- url/path (uri)
And can be utilized via a variety of dynamic static method calls:
use Pop\Utils\Str; echo Str::titleCaseToKebabCase('TitleCase'); // title-case echo Str::titleCaseToSnakeCase('TitleCase'); // title_case echo Str::camelCaseToDash('camelCase'); // camel-case echo Str::camelCaseToUnderscore('camelCase'); // camel_case echo Str::kebabCaseToTitleCase('kebab-string'); // KebabString echo Str::snakeCaseToCamelCase('snake_case_string'); // SnakeCaseString echo Str::snakeCaseToNamespace('snake_case_string'); // Snake\Case\String echo Str::kebabCaseToPath('kebab-string'); // kebab/string (kebab\string on Windows) echo Str::camelCaseToUrl('camelCase'); // camel/case
Number Helper
The Pop\Utils\Num class has a number of static methods to assist in
manipulating and formatting numbers:
Num::float(mixed $number, string $separator = '', string $decimal = '.', int $precision = 2): stringNum::currency(mixed $number, string $currency = '$', string $separator = ',', string $decimal = '.', int $precision = 2): stringNum::percentage(mixed $number, int $precision = 2, string $decimal = '.'): stringNum::convertPercentage(mixed $number, int $precision = 2, string $decimal = '.'): stringNum::abbreviate(mixed $number, int $precision = 2, bool $uppercase = true, string $space = ''): stringNum::readable(mixed $number, bool $case = true): string
UUID Helper
The Pop\Utils\Uuid class has a few static methods to assist in the generation of V4 and V7 UUIDs:
Uuid::v4(): stringUuid::v4Linux(): stringUuid::v4LinuxAvailable(): boolUuid::v7(): string
use Pop\Utils\Uuid; // Generate a v4 UUID (random) using native PHP echo Uuid::v4(); // Generate a v4 UUID (random) using the Linux random/uuid file if (Uuid::v4LinuxAvailable()) { echo Uuid::v4Linux(); } // Generate a v7 UUID (time-based) using native PHP echo Uuid::v7();
Helper Functions
There is a set of "helper" functions to assist with quick manipulation of data like
strings, arrays, and dates. The functions themselves can be loaded manually by including the
functions.php file in this repository, or they can be loaded using the Pop\Utils\Helper
class functions:
use Pop\Utils\Helper; if (!Helper::isLoaded()) { Helper::loadFunctions(); }
The above is automatically executed in a Pop\Application object's bootstrap method, unless
it is disabled by the config setting of 'helper_functions' => false.
The included functions are:
app_date(string $format, ?int $timestamp = null, string $env = 'APP_TIMEZONE', mixed $envDefault = null): string|nullstr_slug(string $string, string $separator = '-'): stringstr_random(int $length, int $case = Str::MIXEDCASE): stringstr_random_alpha(int $length, int $case = Str::MIXEDCASE): stringstr_random_num(int $length): stringstr_random_alphanum(int $length, int $case = Str::MIXEDCASE): stringstr_from_camel(string $string, ?string $separator = '-', bool $preserveCase = false): stringstr_to_camel(string $string): stringstr_title_case(string $string): stringstr_snake_case(string $string, bool $preserveCase = false): stringstr_kebab_case(string $string, bool $preserveCase = false): stringarray_collapse(array|AbstractArray $array): arrayarray_flatten(array|AbstractArray $array, int|float $depth = INF): arrayarray_divide(array|AbstractArray $array): arrayarray_join(array|AbstractArray $array, string $glue, string $finalGlue = ''): stringarray_prepend(array|AbstractArray $array, mixed $value, mixed $key = null): arrayarray_pull(array &$array, mixed $key): mixedarray_sort(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $assoc = true, bool $descending = false): arrayarray_sort_desc(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $assoc = true): arrayarray_ksort(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $descending = false): arrayarray_ksort_desc(array|AbstractArray $array, int $flags = SORT_REGULAR): arrayarray_usort(array|AbstractArray $array, mixed $callback, bool $assoc = true): arrayarray_uksort(array|AbstractArray $array, mixed $callback): arrayarray_make(mixed $value): array
popphp/pop-utils 适用场景与选型建议
popphp/pop-utils 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 33.95k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2019 年 12 月 24 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「utilities」 「pop」 「pop php」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 popphp/pop-utils 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 popphp/pop-utils 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 popphp/pop-utils 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Pop Http Component for Pop PHP Framework
Pop PHP Framework, a lightweight, robust PHP framework
Pop Debug Component for Pop PHP Framework
Pop Log Component for Pop PHP Framework
Pop Console Component for Pop PHP Framework
Pop View Component for Pop PHP Framework
统计信息
- 总下载量: 33.95k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 15
- 依赖项目数: 15
- 推荐数: 0
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2019-12-24