> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Collection Deep Dive

> 從歷史沿革、類別結構、PHPDoc Generics 與閱讀方式的觀點，解說 Laravel Collection 的實作。

## 本頁的目的

本頁不是介紹 `collect()` 的用法，而是提供閱讀 Laravel 本體實作原始碼的地圖。

適合已熟悉 `Collection` 方法清單、想進一步理解「為何採此設計」的讀者。

## 歷史沿革

Collection 的結構在導入 `LazyCollection` 時經過大幅整理。

### Laravel 5.8 以前

* `Illuminate\Support\Collection`
* `Illuminate\Database\Eloquent\Collection`（繼承 `Collection`）

此時尚不存在 `LazyCollection`、`Enumerable`、`EnumeratesValues`。

* [5.8 的 Collection.php](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Support/Collection.php)
* [5.8 的 Eloquent Collection.php](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Eloquent/Collection.php)

### Laravel 6.0 的變更

隨著加入 `LazyCollection`，共通 API 被分離為 `Enumerable`（介面）與 `EnumeratesValues`（trait）的結構。

* [6.x 的 LazyCollection.php](https://github.com/laravel/framework/blob/6.x/src/Illuminate/Support/LazyCollection.php)
* [6.x 的 Enumerable.php](https://github.com/laravel/framework/blob/6.x/src/Illuminate/Support/Enumerable.php)
* [6.x 的 EnumeratesValues.php](https://github.com/laravel/framework/blob/6.x/src/Illuminate/Support/Traits/EnumeratesValues.php)

## 現在的整體結構（Laravel 13）

> 參照：[laravel/framework v13.x](https://github.com/laravel/framework/tree/13.x/src/Illuminate)

```mermaid theme={null}
classDiagram
    class Enumerable {
      <<interface>>
    }
    class EnumeratesValues {
      <<trait>>
    }
    class Collection
    class LazyCollection
    class EloquentCollection

    Collection ..|> Enumerable : implements
    LazyCollection ..|> Enumerable : implements
    Collection ..> EnumeratesValues : use
    LazyCollection ..> EnumeratesValues : use
    EloquentCollection --|> Collection : extends

    note for Enumerable "共通 API 的<br>Contract"
    note for EnumeratesValues "共通方法的<br>實作本體"
    note for Collection "於記憶體中<br>立即求值"
    note for LazyCollection "基於 Generator 的<br>延遲求值"
    note for EloquentCollection "為 Eloquent Model<br>擴充"
```

* [Collection.php](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Collections/Collection.php)
* [LazyCollection.php](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Collections/LazyCollection.php)
* [EnumeratesValues.php](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Collections/Traits/EnumeratesValues.php)
* [Enumerable.php](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Collections/Enumerable.php)
* [Eloquent Collection.php](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Eloquent/Collection.php)

<Info>
  目前實體檔案路徑為 `src/Illuminate/Collections/*`，但命名空間仍保留為 `Illuminate\\Support`。閱讀原始碼時請將「路徑」與「namespace」分開來確認。
</Info>

## PHPDoc 與 PHPStan 風格的 Generics

PHP 本身沒有 Generics。
即便如此，Collection 相關程式碼透過 PHPDoc 表達了強型別資訊。

主要目的有二：

* 讓 IDE 補完精準
* 提升 PHPStan / Larastan 等靜態分析的精度

### 常見的寫法

```php theme={null}
/**
 * @template TKey of array-key
 * @template-covariant TValue
 * @implements \Illuminate\Support\Enumerable<TKey, TValue>
 */
class Collection implements Enumerable
{
    /**
     * @use \Illuminate\Support\Traits\EnumeratesValues<TKey, TValue>
     */
    use EnumeratesValues;
}
```

| 寫法                              | 意義                        |
| ------------------------------- | ------------------------- |
| `@template TKey of array-key`   | 將 key 型別限制為 `int\|string` |
| `@template-covariant TValue`    | 將值型別視為共變（能安全地替換為更具體的型別）   |
| `@implements ...<TKey, TValue>` | 傳遞型別引數至實作的介面              |
| `@extends ...<TKey, TModel>`    | 宣告繼承父類別時的型別引數             |
| `@use ...<TKey, TValue>`        | 宣告套用 trait 時的型別引數         |

### 於 Eloquent Collection 的樣貌

```php theme={null}
/**
 * @template TKey of array-key
 * @template TModel of \Illuminate\Database\Eloquent\Model
 * @extends \Illuminate\Support\Collection<TKey, TModel>
 */
class Collection extends BaseCollection
{
}
```

`TValue` 被具體化為 `TModel`，因此 `map()`、`filter()` 等的型別推斷可強化為 Eloquent 模型導向。

## 閱讀實作時的順序

### 1. 從 `Enumerable` 入手

先掌握「所提供的契約為何」。
掌握此處的方法清單後，後續閱讀實作會更迅速。

### 2. 沿著 `EnumeratesValues` 追蹤共通方法

`map`、`filter`、`reduce` 等大量共通邏輯皆在此。
之後只看 `Collection` 與 `LazyCollection` 之間的差異即可，減少略讀。

### 3. 比較 `Collection` 與 `LazyCollection` 的差異

* `Collection`：持有陣列並立即求值
* `LazyCollection`：使用 `Generator` 延遲求值

即使是同名方法，求值時機與記憶體特性也不同。

### 4. 最後閱讀 `Eloquent\Collection`

集中在 `find`、`load`、`modelKeys` 等針對模型集合的擴充。
於理解基底 `Collection` 後再閱讀，其意圖會更易懂。

<Tip>
  深入探討單一方法時，依 `Enumerable` 的宣告 → `EnumeratesValues` 的本體 → `Collection` / `LazyCollection` 是否覆寫的順序追蹤，就不會迷路。
</Tip>

## 相關頁面

* [Collection](/zh-TW/collections)
* [Collection 的 Higher Order Messages](/zh-TW/advanced/higher-order-messages)
* [Macroable trait](/zh-TW/advanced/macroable)


## Related topics

- [进阶主题](/zh-CN/advanced/index.md)
- [Welcome](/index.md)
- [Collection 的 Higher Order Messages](/zh-TW/advanced/higher-order-messages.md)
- [Laravel Bluesky](/zh-TW/packages/laravel-bluesky/index.md)
- [Laravel Console Starter](/zh-TW/packages/laravel-console-starter/index.md)
