omegaalfa/collection 问题修复 & 功能扩展

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

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

omegaalfa/collection

Composer 安装命令:

composer require omegaalfa/collection

包简介

This library implements the Trie routing logic

README 文档

README

🚀 PHP Collection Library

PHP Version License Tests Coverage PHPStan

A powerful, type-safe PHP collection library with eager & lazy evaluation 🎯

FeaturesInstallationQuick StartDocumentationExamples

✨ Features

🎯 Type-Safe

Full PHPDoc generics support

Sequence<User>
Map<string, Config>

Lazy Evaluation

Memory-efficient processing

LazySequence::range(1, 1M)
  ->take(10) // Only 10 iterations!

🔒 Immutable

Readonly data structures

$new = $seq->append(42);
// Original unchanged
  • 7 Specialized Classes - Collection, Sequence, Map, LazySequence, LazyMap, LazyFileIterator, LazyProxyObject
  • 150+ Methods - Rich API with fluent interface
  • Modern PHP - PHP 8.3+ with strict types & readonly properties
  • Well Tested - 239 tests, 80.85% coverage
  • Zero Dependencies - Pure PHP, no external packages required

📦 Installation

composer require omegaalfa/collection

Requirements

Requirement Version Note
PHP >= 8.3 Required
PHP >= 8.4 Recommended for LazyProxyObject

🎯 Core Concepts

Class Type Purpose Use Case
Collection Generic Iterator wrapper with transformations ✅ Mixed data, legacy code, Iterator support
Sequence Eager Ordered immutable list ✅ Small lists, type safety, immutability
Map Eager Immutable key-value dictionary ✅ Small maps, type safety, immutability
LazySequence Lazy Generator-based pipeline ✅ Large datasets, streaming, memory efficiency
LazyMap Lazy Lazy value computation ✅ Expensive computations, caching, DI
LazyFileIterator Lazy File streaming (JSON lines) ✅ Large files, memory constraints
LazyProxyObject Lazy PHP 8.4+ lazy object instantiation ✅ Expensive objects, service containers

� Quick Start

💡 Collection - Generic Wrapper

Click to expand
use Omegaalfa\Collection\Collection;

// Create from array or Iterator
$collection = new Collection([1, 2, 3, 4, 5]);

// Transform (eager)
$doubled = $collection->map(fn($x) => $x * 2);
$evens = $collection->filter(fn($x) => $x % 2 === 0);

// 🚀 Lazy methods (memory efficient!)
$result = Collection::lazyRange(1, 1000000)
    ->lazyMap(fn($x) => $x * 2)
    ->lazyFilter(fn($x) => $x > 100)
    ->lazyTake(10);  // Only processes ~51 elements!

// Array access
$collection['key'] = 'value';
echo $collection['key'];

// Statistics
echo $collection->sum();    // 15
echo $collection->avg();    // 3
echo $collection->count();  // 5

📋 Sequence - Ordered Immutable List

Click to expand
use Omegaalfa\Collection\Sequence;

// Create
$numbers = Sequence::of(1, 2, 3, 4, 5);
$range = Sequence::range(1, 10);

// Immutable transformations
$doubled = $numbers->map(fn($x) => $x * 2);
$evens = $numbers->filter(fn($x) => $x % 2 === 0);

// 🔗 Fluent chaining
$result = Sequence::range(1, 100)
    ->filter(fn($x) => $x % 3 === 0)
    ->map(fn($x) => $x * $x)
    ->take(5);

// Access
echo $numbers->at(0);      // 1
echo $numbers->first();    // 1
echo $numbers->last();     // 5

// Operations (returns new Sequence)
$appended = $numbers->append(6);
$prepended = $numbers->prepend(0);
$inserted = $numbers->insert(2, 99);
$removed = $numbers->remove(2);

🗺️ Map - Immutable Key-Value Dictionary

Click to expand
use Omegaalfa\Collection\Map;

// Create
$user = Map::of(
    'name', 'John',
    'age', 30,
    'city', 'NY'
);

// Access
echo $user->get('name');               // John
echo $user->getOrDefault('email', '-'); // -

// Transform (returns new Map)
$aged = $user->put('age', 31);
$removed = $user->remove('city');

// 🔄 Transformations
$uppercased = $user->mapValues(fn($k, $v) => is_string($v) ? strtoupper($v) : $v);
$prefixed = $user->mapKeys(fn($k) => "user_$k");

// Merge
$merged = $user->merge(Map::of('email', 'john@example.com'));

⚡ LazySequence - Generator-Based Pipeline

Click to expand
use Omegaalfa\Collection\LazySequence;

// 🚀 Pipeline - NOTHING executes until iteration!
$pipeline = LazySequence::range(1, 1000000)
    ->map(fn($x) => $x * 2)
    ->filter(fn($x) => $x > 100)
    ->take(10);

// Now it executes - only ~51 iterations!
foreach ($pipeline as $value) {
    echo $value;  // 102, 104, 106...
}

// ⚡ Short-circuit operations
$first = LazySequence::range(1, 1000000)->first();  // Stops at 1

// Materialize to eager
$eager = $lazy->toEager();  // Returns Sequence

🎯 LazyMap - Lazy Value Computation

Click to expand
use Omegaalfa\Collection\LazyMap;

// Values are closures - computed on-demand! 💡
$config = LazyMap::from([
    'database' => fn() => new Database(),  // Not created yet
    'cache' => fn() => new Redis(),        // Not created yet
    'api' => fn() => new ApiClient()       // Not created yet
]);

// ⚡ Only creates Database when accessed
$db = $config->get('database');

// 🆕 With LazyProxyObject (PHP 8.4+)
$services = LazyMap::ofLazyObjects([
    'logger' => [Logger::class, $config],
    'mailer' => [Mailer::class, $smtp]
]);

// Creates lazy proxy - object instantiated on first method call
$logger = $services->get('logger');
$logger->info('message');  // NOW Logger is instantiated

📁 LazyFileIterator - Stream Large Files

Click to expand
use Omegaalfa\Collection\LazyFileIterator;

// 📄 Stream JSON lines file (memory efficient!)
$iterator = new LazyFileIterator('data.jsonl');

foreach ($iterator as $index => $object) {
    echo "Line {$index}: {$object->name}\n";
}

// Use with Collection for transformations
$collection = new Collection($iterator);
$filtered = $collection->lazyFilter(fn($obj) => $obj->active);

🎯 Choosing the Right Class

Use Collection 💡

  • ✅ Working with Iterator instances
  • ✅ Need array-like access (ArrayAccess)
  • ✅ Want both eager and lazy methods
  • ✅ Migrating legacy code

Use Sequence 📋

  • ✅ Need ordered list (0-indexed)
  • ✅ Want immutability
  • ✅ Working with small-to-medium datasets
  • ✅ Type safety is important

Use Map 🗺️

  • ✅ Need key-value pairs
  • ✅ Want immutability
  • ✅ Working with configuration, dictionaries
  • ✅ Type safety is important

Use LazySequence

  • ✅ Large datasets (millions of items)
  • ✅ Memory is constrained
  • ✅ Need pipeline composition
  • ✅ Can benefit from short-circuit evaluation

Use LazyMap 🎯

  • ✅ Values are expensive to compute
  • ✅ Not all values will be accessed
  • ✅ Need lazy initialization
  • ✅ Dependency injection containers

Use LazyFileIterator 📁

  • ✅ Processing large JSON line files
  • ✅ Cannot load entire file in memory
  • ✅ Streaming data processing

� API Reference

🔥 Core Methods - Quick Reference

🔄 Transformation

map(callable $fn): self           // Transform each element
filter(callable $fn): self        // Keep matching elements
flatMap(callable $fn): self       // Map + flatten
reduce(callable $fn, mixed $init) // Reduce to single value

📊 Aggregation

sum(): int|float                  // Sum all numeric values
avg(): int|float                  // Calculate average
min(): mixed                      // Find minimum
max(): mixed                      // Find maximum
count(): int                      // Count elements

🔍 Retrieval

first(): mixed                    // Get first element
last(): mixed                     // Get last element
find(callable $fn): mixed         // Find matching element
any(callable $fn): bool           // Check if any matches
all(callable $fn): bool           // Check if all match

⚡ Lazy Operations

take(int $n): self               // Take first n elements
skip(int $n): self               // Skip first n elements
chunk(int $size): self           // Split into chunks
takeWhile(callable $fn): self    // Take while predicate true
skipWhile(callable $fn): self    // Skip while predicate true
📋 Full Method Compatibility Matrix
Method Collection Sequence Map LazySequence LazyMap
map
filter
reduce
take
skip
chunk
sort
reverse
unique
merge
keys
values
mapKeys
mapValues

📖 Complete documentation: docs/API.md150+ methods documented

⚡ Performance & Optimization

💾 Memory Efficiency

Traditional Approach ❌

// Processes 1M elements
$data = range(1, 1000000);
$result = array_map(
    fn($x) => $x * 2,
    array_filter($data, fn($x) => $x % 2 === 0)
);

Result: ~400 MB | ~850ms

Lazy Evaluation ✅

// Only processes 51 elements!
$result = LazySequence::range(1, 1000000)
    ->map(fn($x) => $x * 2)
    ->filter(fn($x) => $x > 100)
    ->take(10);

Result: ~2 MB | ~0.7ms
🚀 2290x FASTER!

📊 Benchmark Results

View Detailed Benchmarks
📊 Processing 1,000,000 items:

Traditional Array:        ~400 MB peak | ~850ms
Collection (eager):       ~380 MB peak | ~820ms
LazySequence:            ~2 MB peak   | ~12ms   ⚡ 70x faster
LazyFileIterator:        ~1 MB peak   | ~8ms    ⚡ 106x faster

Operation: map → filter → take(100)

Implementation Time Memory vs Array
Array 850ms 400 MB baseline
Collection 820ms 380 MB 1.04x faster
LazySequence 12ms 2 MB 70x faster
LazyFileIterator 8ms 1 MB 106x faster

🎯 Lazy vs Eager Trade-offs

Scenario Use Lazy ⚡ Use Eager 🏃
Large datasets (100k+) ✅ Memory efficient ❌ High memory
Expensive operations ✅ Deferred execution ❌ Upfront cost
Short-circuit (take, first) ✅ Early termination ❌ Full processing
Multiple transformations ✅ Single-pass ❌ Multiple passes
Small datasets (<1k) ❌ Overhead ✅ Fast
Random access ❌ Must materialize ✅ Direct access

🔍 Detailed analysis: docs/PROFILING_ANALYSIS.md

🧪 Testing

# Run all tests
composer test

# Run with coverage report
composer test:coverage

# Static analysis (PHPStan level 9)
composer phpstan

📊 Code Quality Metrics

Metric Value Status
Tests 239 tests
Assertions 374 assertions
Line Coverage 80.85%
Method Coverage 76.92%
PHPStan Level Max (9)

📖 Documentation

📘 Core Documentation

💡 Examples & Guides

🏆 Benchmark

Run the included benchmark script:

php benchmark.php
Sample Output
🎯 Collection Library Benchmark
================================

📊 Test: map + filter + take(100) on 1,000,000 items

✅ Traditional Array:     850ms  |  400 MB
✅ Collection (eager):    820ms  |  380 MB
✅ LazySequence:          12ms   |  2 MB    🚀 70x faster
✅ LazyFileIterator:      8ms    |  1 MB    🚀 106x faster

💡 Winner: LazyFileIterator
   - 106x faster
   - 400x less memory
   - Perfect for streaming large datasets

🏗️ Architecture

📐 Class Hierarchy & Design Patterns
Contract/
├── MapInterface           # Contract for Map implementations
└── SequenceInterface      # Contract for Sequence implementations

Traits/
├── CollectionTransformationsTrait  # Transformation operations
├── CollectionAggregatesTrait       # Aggregation operations
├── CollectionArrayAccessTrait      # ArrayAccess implementation
└── LazyOperationsTrait             # Lazy evaluation operations

Core Classes/
├── Collection             # Hybrid: Eager + Lazy operations
├── Sequence              # Immutable ordered list
├── Map                   # Immutable key-value map
├── LazySequence          # Generator-based lazy sequence
└── LazyMap               # Lazy-evaluated map (Closures)

Utilities/
├── LazyProxyObject       # PHP 8.4+ lazy object proxies
└── LazyFileIterator      # Stream large files efficiently

File Parsers/
├── ParserInterface
├── JsonLinesParser       # Parse .jsonl files
├── CsvParser             # Parse CSV files
├── TsvParser             # Parse TSV files
└── PlainTextParser       # Parse plain text

🎨 Design Principles

✅ Core Principles

  • Immutability: All transformations return new instances
  • Lazy Evaluation: Defer computation until needed
  • Type Safety: Full PHPDoc generics support
  • Interface Contracts: Clear API boundaries

🌟 Inspired By

📄 License

This project is licensed under the MIT License
See the LICENSE file for details

Permission is hereby granted, free of charge, to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software.

🤝 Contributing

Contributions are welcome! 🎉

📝 How to Contribute

  1. 🍴 Fork the repository
  2. 🌿 Create a feature branch
    git checkout -b feature/amazing-feature
  3. Ensure all tests pass
    composer test
    composer phpstan
  4. 📝 Commit your changes
    git commit -m 'feat: add amazing feature'
  5. 📤 Push to the branch
    git push origin feature/amazing-feature
  6. 🎉 Open a Pull Request

📋 Contribution Guidelines

Requirement Description
Tests All tests must pass (composer test)
PHPStan Level 9 compliance required
Coverage Maintain >75% code coverage
PSR-12 Follow PHP coding standards
Conventional Commits Use semantic commit messages

💬 Support & Community

Channel Link Description
🐛 Issues GitHub Issues Bug reports & feature requests
💡 Discussions GitHub Discussions Questions & ideas
📧 Email support@omegaalfa.dev Direct support
📖 Docs Documentation Complete guides

⭐ Star History

Star History Chart

Made with ❤️ by the Omegaalfa Team

Star this repo if you find it useful!

📖 Documentation💡 Examples📝 Changelog📄 License

omegaalfa/collection 适用场景与选型建议

omegaalfa/collection 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 17 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 06 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 omegaalfa/collection 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-06-23