petrobolos/fixed-array-functions 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

petrobolos/fixed-array-functions

Composer 安装命令:

composer require petrobolos/fixed-array-functions

包简介

Laravel helper methods for working with high performance SPL fixed arrays.

README 文档

README

Latest Version on Packagist GitHub issues GitHub Tests Action Status GitHub Code Style Action Status Total Downloads GitHub

SplFixedArrays are an implementation of a traditional, bounded array in the PHP standard library.

While they require manual resizing, they're significantly faster than regular arrays or collections when working with large sets of data.

Requirements

Currently, requires PHP 8.4 or above, and Laravel 12+.

Installation

You can install the package via Composer:

composer require petrobolos/fixed-array-functions

Quick Start

Fluent interface

FixedArray is best used with its fluent interface. If you're familiar with Illuminate collections, you'll feel right at home. Provide it an SplFixedArray to get started, or a standard array or collection that will be automatically converted.

use Petrobolos\FixedArray\FixedArrayable;

// Create using various methods
$array = new FixedArrayable([1, 2, 3]);
$array = fixedArray([1, 2, 3]);  // Helper function
$array = FixedArrayable::fromCollection(collect([1, 2, 3]));

// Chain methods just like Laravel Collections
$result = fixedArray([1, 2, 3, 4, 5, 6])
    ->filter(fn ($value) => $value % 2 === 0)
    ->map(fn ($value) => $value * 2)
    ->sum();  // Returns 24 (2*2 + 4*2 + 6*2)

Static methods

You aren't forced to use the fluent interface and can access methods directly by calling them. This is useful if you only need to do one or two operations on a fixed array.

use Petrobolos\FixedArray\FixedArray;

$arr = FixedArray::fromArray([1, 2, 3, 4, 5]);

// Aggregate functions
$sum = FixedArray::sum($arr);           // 15
$avg = FixedArray::avg($arr);           // 3
$min = FixedArray::min($arr);           // 1
$max = FixedArray::max($arr);           // 5

// Higher-order functions
$doubled = FixedArray::map($arr, fn($v) => $v * 2);
$evens = FixedArray::filter($arr, fn($v) => $v % 2 === 0);

// Conditional operations
$result = FixedArray::when(
    $arr,
    fn($a) => FixedArray::count($a) > 3,
    fn($a) => FixedArray::push($a, 6)
);

Real-World Examples

Processing Large Datasets

// Efficiently process 100,000 records
$data = FixedArray::create(100000);

for ($i = 0; $i < 100000; $i++) {
    FixedArray::offsetSet($data, $i, fetchRecordFromDatabase($i));
}

$processed = fixedArray($data)
    ->filter(fn($record) => $record->isActive)
    ->map(fn($record) => $record->transform())
    ->toCollection(); // Convert back to Collection for further Laravel operations

Data Aggregation

$orders = fixedArray($orderArray)
    ->pluck('total')
    ->sum();

$averageAge = fixedArray($users)
    ->avg('age');

$oldestUser = fixedArray($users)
    ->max('created_at');

Conditional Transformations

$processed = fixedArray($items)
    ->when(
        $shouldFilter,
        fn($arr) => $arr->filter(fn($item) => $item->isValid())
    )
    ->unless(
        $skipSorting,
        fn($arr) => $arr->sort()
    )
    ->tap(fn($arr) => logger()->info('Processed items', ['count' => $arr->count()]))
    ->toArray();

Partitioning Data

[$valid, $invalid] = fixedArray($records)
    ->partition(fn($record) => $record->validate())
    ->toArray();

// $valid contains all validated records
// $invalid contains all failed records

Performance Benefits

SplFixedArray offers significant performance advantages over standard PHP arrays for large datasets:

  • Memory Efficiency: Uses approximately 50% less memory than standard arrays
  • Faster Access: Direct memory access without hash table overhead
  • Predictable Performance: O(1) access time for all operations

When to use SplFixedArray:

  • Working with large datasets (10,000+ elements)
  • Memory-constrained environments
  • Performance-critical array operations
  • Known array size at creation time

When to stick with regular arrays/Collections:

  • Small datasets (< 1,000 elements)
  • Dynamic sizing with frequent additions/removals
  • Need associative keys or complex key types

Full list of available methods

Method Description
add Alias for push.
addFrom Add an array or collection of items to a fixed array.
all Alias for every.
avg Calculate the average of numeric values.
average Alias for avg.
chunk Split a fixed array into chunks of a given size.
chunkWhile Split a fixed array into chunks while a callback returns true.
contains Check whether an item exists in a fixed array.
count Return the number of elements.
create Create a new fixed array of a given size.
dsfargeg DSFARGEG
each Apply a callback to each item without modifying the original array.
every Determine if all items pass a given test.
fill Fill the array with a single value.
filter Filter the array using a callback (passes key to callback).
find Return the first element matching a callback.
findKey Return the key of the first element matching a callback.
findIndex Alias for findKey.
first Return the first element of the array.
flatten Flatten nested arrays, collections, and fixed arrays.
fluent Creates a new fluent interface for chaining methods.
fromArray Create a fixed array from a standard array.
fromCollection Create a fixed array from an Illuminate collection.
getSize Return the number of elements in the array.
implode Alias for join.
isEmpty Check if the array is empty.
isFixedArray Check whether a value is a fixed array.
isNotEmpty Check if the array is not empty.
join Join array elements with a string.
keys Get all keys (indices) from the array.
last Return the last element of the array.
map Apply a callback to each item and return a new array.
max Find the maximum value.
merge Merge multiple arrays, fixed arrays, or collections.
min Find the minimum value.
nullify Replace all elements with null.
offsetExists Check if an index exists in the array.
offsetGet Get the value at a specific index.
offsetNull Set a specific index to null.
offsetSet Set a value at a specific index.
partition Split array into two groups based on a callback.
pipe Pass the array through a callback and return the result.
pluck Extract values from a specific property or key.
pop Remove and return the last element.
push Add a value to the first available space.
random Return a random element from the array.
reduce Reduce the array to a single value using a callback.
reject Filter out items that pass the test (opposite of filter).
resize Alias for setSize.
reverse Reverse the order of elements.
second Return the second element.
setSize Resize the array to a given size.
shift Remove and return the first element.
shuffle Shuffle the array in a secure manner.
slice Return a subset of the array.
some Determine if at least one item passes a given test.
sort Sort the array optionally using a callback.
sum Sum all numeric values in the array.
tap Pass the array to a callback and return the array.
toArray Convert the fixed array into a standard PHP array.
toCollection Convert the fixed array into an Illuminate collection.
unique Remove duplicate values from the array.
unshift Prepend one or more values to the array.
unless Apply callback if the condition is false.
values Get all values from the array (reindexed).
when Apply callback if the condition is true.

Testing

Tests are run using Pest. You can run the suite like so:

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

We welcome pull requests, especially those improving the package's optimisation and speed, and new features to bring it into parity with Collection.

Please ensure any functionality submitted has adequate test coverage and documentation (at least in English.)

License

The MIT License (MIT). Please see License File for more information.

petrobolos/fixed-array-functions 适用场景与选型建议

petrobolos/fixed-array-functions 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 66 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 05 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「array」 「laravel」 「collection」 「splfixedarray」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 petrobolos/fixed-array-functions 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 petrobolos/fixed-array-functions 我们能提供哪些服务?
定制开发 / 二次开发

基于 petrobolos/fixed-array-functions 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 66
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 10
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-05-05