omegaalfa/collection
Composer 安装命令:
composer require omegaalfa/collection
包简介
This library implements the Trie routing logic
README 文档
README
🚀 PHP Collection Library
A powerful, type-safe PHP collection library with eager & lazy evaluation 🎯
Features • Installation • Quick Start • Documentation • Examples
✨ Features
- ✅ 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
� 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.md • 150+ methods documented
⚡ Performance & Optimization
💾 Memory Efficiency
📊 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
|
🌟 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
- 🍴 Fork the repository
- 🌿 Create a feature branch
git checkout -b feature/amazing-feature
- ✅ Ensure all tests pass
composer test composer phpstan - 📝 Commit your changes
git commit -m 'feat: add amazing feature' - 📤 Push to the branch
git push origin feature/amazing-feature
- 🎉 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 |
| support@omegaalfa.dev | Direct support | |
| 📖 Docs | Documentation | Complete guides |
⭐ Star History
Made with ❤️ by the Omegaalfa Team
⭐ Star this repo if you find it useful!
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 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 omegaalfa/collection 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A set of useful PHP classes.
repository php library
PHP Library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way
This package provides type-safe extension of the laravel collection, forcing a single type of object.
Trait providing methods to set class properties with an array.
Traits to build collections of specific objects
统计信息
- 总下载量: 17
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 29
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-06-23