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

# Fluent 類別

> 說明如何使用 Illuminate\Support\Fluent 類別將陣列資料以物件方式處理。這是自 Laravel 初期就存在的隱藏便利類別。

## 什麼是 Fluent 類別

`Fluent` 類別是可將陣列以物件方式處理的通用工具類別。實作於 `Illuminate\Support\Fluent`，雖然從 Laravel 初期版本就存在，但官方文件中幾乎未提及。

內部以屬性管理陣列，透過魔術方法（`__get` / `__set` / `__call`）實現類似屬性的讀寫。

<Tip>
  Laravel 11 新增了 `fluent()` helper，Fluent 類別也獲得強化，正是現在該加以活用的優秀類別。
</Tip>

## 建立實例

### 建構函式

```php theme={null}
use Illuminate\Support\Fluent;

// 以陣列初始化
$user = new Fluent(['name' => 'Laravel', 'type' => 'Framework']);

echo $user->name; // 'Laravel'
echo $user->type; // 'Framework'
```

### make() 工廠方法

```php theme={null}
use Illuminate\Support\Fluent;

$config = Fluent::make([
    'host' => 'localhost',
    'port' => 3306,
    'database' => 'laravel'
]);

echo $config->host; // 'localhost'
```

### fluent() helper 函式

Laravel 11 新增了 `fluent()` helper。等同於 `Fluent::make()`。

```php theme={null}
$request = fluent([
    'method' => 'POST',
    'path' => '/api/users',
    'status' => 201
]);

echo $request->method; // 'POST'
```

## 屬性存取

### 動態屬性讀寫

```php theme={null}
$fluent = new Fluent();

// 寫入
$fluent->name = 'Laravel';
$fluent->version = 13;

// 讀取
echo $fluent->name;    // 'Laravel'
echo $fluent->version; // 13
```

### 方法鏈

透過 `__call` 魔術方法，呼叫不存在的方法即可設定屬性。方法會回傳 `$this`，因此可以鏈式串接。

```php theme={null}
$config = new Fluent();

$config
    ->host('localhost')
    ->port(3306)
    ->database('laravel')
    ->username('root')
    ->password('secret');

echo $config->host;     // 'localhost'
echo $config->password; // 'secret'
```

此機制讓您可以流暢的 API（Fluent Interface）取代陣列來設定值。

## 主要方法

### get() — 以點記法存取

```php theme={null}
$user = new Fluent([
    'profile' => [
        'email' => 'user@example.com',
        'phone' => '090-xxxx-xxxx'
    ]
]);

// 以點記法取得巢狀值
$email = $user->get('profile.email'); // 'user@example.com'
$phone = $user->get('profile.phone'); // '090-xxxx-xxxx'

// 可指定預設值
$fax = $user->get('profile.fax', 'N/A'); // 'N/A'
```

### set() — 以點記法設定

```php theme={null}
$fluent = new Fluent();

$fluent->set('user.name', 'Laravel');
$fluent->set('user.email', 'laravel@example.com');

print_r($fluent->toArray());
// Array (
//     [user] => Array (
//         [name] => Laravel
//         [email] => laravel@example.com
//     )
// )
```

### fill() — 一次設定多個屬性

```php theme={null}
$fluent = new Fluent(['initial' => 'value']);

$fluent->fill([
    'name' => 'Laravel',
    'version' => 13,
    'license' => 'MIT'
]);

echo $fluent->name;    // 'Laravel'
echo $fluent->version; // 13
```

### all() — 以陣列取得所有屬性

```php theme={null}
$fluent = fluent([
    'name' => 'Laravel',
    'version' => 13,
    'license' => 'MIT'
]);

// 所有屬性
$all = $fluent->all();
// ['name' => 'Laravel', 'version' => 13, 'license' => 'MIT']

// 僅取特定屬性
$subset = $fluent->all(['name', 'license']);
// ['name' => 'Laravel', 'license' => 'MIT']
```

### scope() — 將巢狀值轉換為新的 Fluent

```php theme={null}
$config = fluent([
    'database' => [
        'host' => 'localhost',
        'port' => 3306,
        'name' => 'laravel'
    ]
]);

$dbConfig = $config->scope('database');
// $dbConfig 為全新的 Fluent 實例

echo $dbConfig->host; // 'localhost'
echo $dbConfig->port; // 3306
```

如此便可將巢狀陣列視為獨立的 Fluent 物件來處理。

### value() — 以 callback 動態指定預設值

```php theme={null}
$user = fluent(['role' => 'admin']);

// key 存在時回傳其值
$role = $user->value('role'); // 'admin'

// key 不存在時回傳預設值
$status = $user->value('status', 'active');
// 'active'

// 以 callback 指定預設值
$timestamp = $user->value('updated_at', function () {
    return now()->toIso8601String();
});
```

## 陣列操作

### toArray() — 轉換為陣列

```php theme={null}
$fluent = fluent(['name' => 'Laravel', 'version' => 13]);

$array = $fluent->toArray();
// ['name' => 'Laravel', 'version' => 13]

print_r($array);
```

### getAttributes() — 直接存取內部屬性

```php theme={null}
$fluent = fluent(['a' => 1, 'b' => 2]);

$attributes = $fluent->getAttributes();
// ['a' => 1, 'b' => 2]
```

### ArrayAccess 介面

Fluent 實作了 `ArrayAccess`，因此可以像陣列一樣操作。

```php theme={null}
$config = new Fluent();

// 以陣列方式設定
$config['host'] = 'localhost';
$config['port'] = 3306;

// 以陣列方式讀取
echo $config['host']; // 'localhost'

// 存在確認
if (isset($config['port'])) {
    echo $config['port'];
}

// 刪除
unset($config['port']);
```

### IteratorAggregate 介面

Fluent 可以用 foreach 迴圈。

```php theme={null}
$settings = fluent([
    'debug' => true,
    'cache' => 'redis',
    'queue' => 'database'
]);

foreach ($settings as $key => $value) {
    echo "$key: $value\n";
    // debug: 1
    // cache: redis
    // queue: database
}
```

## JSON 處理

### toJson() — 轉換為 JSON 字串

```php theme={null}
$response = fluent([
    'success' => true,
    'data' => ['id' => 1, 'name' => 'User']
]);

$json = $response->toJson();
// {"success":true,"data":{"id":1,"name":"User"}}

// 可用於 API 回應
return $json;
```

### toPrettyJson() — 轉換為排版後的 JSON

```php theme={null}
$data = fluent([
    'users' => [
        ['id' => 1, 'name' => 'Alice'],
        ['id' => 2, 'name' => 'Bob']
    ]
]);

echo $data->toPrettyJson();
// {
//     "users": [
//         {
//             "id": 1,
//             "name": "Alice"
//         },
//         {
//             "id": 2,
//             "name": "Bob"
//         }
//     ]
// }
```

### JsonSerializable 介面

Fluent 實作了 `JsonSerializable`，可直接以 `json_encode()` 轉換。

```php theme={null}
$fluent = fluent(['status' => 'ok', 'code' => 200]);

$json = json_encode($fluent);
// {"status":"ok","code":200}

$data = json_decode($json, true);
// ['status' => 'ok', 'code' => 200]
```

## 狀態確認

### isEmpty() / isNotEmpty()

```php theme={null}
$empty = new Fluent();
$filled = fluent(['value' => 1]);

$empty->isEmpty();      // true
$empty->isNotEmpty();   // false

$filled->isEmpty();     // false
$filled->isNotEmpty();  // true
```

## Conditionable trait

Fluent 使用了 `Conditionable` trait，支援有條件的處理。

```php theme={null}
$config = fluent(['env' => 'production']);

$config
    ->when($config->env === 'production', function ($fluent) {
        $fluent->debug = false;
        $fluent->cache = 'redis';
    })
    ->when($config->env === 'local', function ($fluent) {
        $fluent->debug = true;
        $fluent->cache = 'array';
    });

echo $config->debug;
echo $config->cache;
```

透過 `when()` / `unless()` 方法，可以流暢地寫出依條件決定的設定。

## Macroable trait

Fluent 也使用了 `Macroable` trait，可動態新增方法。

```php theme={null}
use Illuminate\Support\Fluent;

// 於 Provider 的 boot() 方法定義
Fluent::macro('isProduction', function () {
    /** @var Fluent $this */
    return $this->env === 'production';
});

Fluent::macro('isDevelopment', function () {
    /** @var Fluent $this */
    return $this->env === 'development';
});

// 使用
$config = fluent(['env' => 'production']);

if ($config->isProduction()) {
    // 正式環境處理
}
```

## 實務使用情境

### API Response Builder

```php theme={null}
namespace App\Support;

use Illuminate\Support\Fluent;

class ApiResponse
{
    public static function success($data = null, string $message = 'Success'): string
    {
        return fluent([
            'success' => true,
            'message' => $message,
            'data' => $data,
            'timestamp' => now()->toIso8601String()
        ])->toJson();
    }

    public static function error(string $message, int $code = 400): string
    {
        return fluent([
            'success' => false,
            'message' => $message,
            'code' => $code,
            'timestamp' => now()->toIso8601String()
        ])->toJson();
    }
}

// 在 Controller 使用
public function store(Request $request)
{
    $user = User::create($request->validated());

    return response()->json(
        json_decode(ApiResponse::success(['id' => $user->id]))
    );
}
```

### Config Builder

```php theme={null}
$dbConfig = fluent()
    ->host(env('DB_HOST', 'localhost'))
    ->port(env('DB_PORT', 3306))
    ->database(env('DB_DATABASE', 'laravel'))
    ->username(env('DB_USERNAME', 'root'))
    ->password(env('DB_PASSWORD', ''))
    ->charset('utf8mb4')
    ->collation('utf8mb4_unicode_ci')
    ->when(env('APP_ENV') === 'production', function ($config) {
        $config->sslmode('require');
        $config->sslcert(env('DB_SSL_CERT'));
    });

// 驗證設定值並使用
config(['database.connections.mysql' => $dbConfig->toArray()]);
```

### 請求參數的驗證與轉換

```php theme={null}
namespace App\Services;

use Illuminate\Support\Fluent;

class SearchFilter
{
    public function apply(array $params): Fluent
    {
        $filter = fluent()
            ->page($params['page'] ?? 1)
            ->perPage($params['per_page'] ?? 15)
            ->sort($params['sort'] ?? 'created_at')
            ->order($params['order'] ?? 'desc')
            ->when(isset($params['search']), function ($f) use ($params) {
                $f->search = $params['search'];
            })
            ->when(isset($params['status']), function ($f) use ($params) {
                $f->status = $params['status'];
            });

        // 分頁計算
        $filter->offset = ($filter->page - 1) * $filter->perPage;

        return $filter;
    }
}

// 使用
$filter = app(SearchFilter::class)->apply(request()->all());

$users = User::query()
    ->when($filter->has('search'), fn ($q) => $q->search($filter->search))
    ->when($filter->has('status'), fn ($q) => $q->where('status', $filter->status))
    ->orderBy($filter->sort, $filter->order)
    ->offset($filter->offset)
    ->limit($filter->perPage)
    ->get();
```

### Model 與 Fluent 的組合

```php theme={null}
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Fluent;

class Post extends Model
{
    protected $casts = [
        'metadata' => 'json'
    ];

    public function getMetadataAttribute($value): Fluent
    {
        return new Fluent($value ?? []);
    }

    public function setMetadataAttribute($value): void
    {
        if ($value instanceof Fluent) {
            $this->attributes['metadata'] = $value->toJson();
        } else {
            $this->attributes['metadata'] = json_encode($value);
        }
    }
}

// 使用
$post = new Post();

$post->metadata = fluent()
    ->title('SEO Title')
    ->description('Meta Description')
    ->keywords(['laravel', 'fluent', 'tutorial'])
    ->author('Laravel Community');

$post->save();

// 讀取
$post = Post::first();
echo $post->metadata->title; // 'SEO Title'
echo $post->metadata->author; // 'Laravel Community'
```

### 表單資料的正規化

```php theme={null}
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Fluent;

class CreateUserRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'name' => 'required|string',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8|confirmed',
            'role' => 'in:user,admin',
            'preferences' => 'json',
        ];
    }

    // 將已驗證的資料以 Fluent 回傳
    public function toFluent(): Fluent
    {
        $preferences = is_string($this->preferences)
            ? json_decode($this->preferences, true)
            : $this->preferences;

        return fluent([
            'name' => $this->name,
            'email' => $this->email,
            'password' => bcrypt($this->password),
            'role' => $this->role ?? 'user',
            'preferences' => new Fluent($preferences ?? [])
        ]);
    }
}

// 在 Controller 使用
public function store(CreateUserRequest $request)
{
    $data = $request->toFluent();

    $user = User::create($data->all());

    return response()->json(['success' => true, 'user_id' => $user->id]);
}
```

## 與其他類別的比較

### Fluent vs Array

| 功能      | Fluent               | Array              |
| ------- | -------------------- | ------------------ |
| 屬性存取    | `$fluent->name`      | `$array['name']`   |
| 方法鏈     | ✓ 支援                 | ✗ 無                |
| JSON 轉換 | `toJson()` 方法        | `json_encode()` 函式 |
| 點記法     | ✓ `get('user.name')` | ✗ 需手動處理            |
| 狀態確認    | `isEmpty()`          | `empty()` 函式       |
| 動態新增方法  | Macroable            | ✗ 不可               |

### Fluent vs Model

| 功能     | Fluent | Model |
| ------ | ------ | ----- |
| DB 永續化 | ✗ 無    | ✓ 自動  |
| 記憶體效率  | ✓ 輕量   | ✗ 較重  |
| 關聯     | ✗ 無    | ✓ 支援  |
| Cast   | ✗ 無    | ✓ 支援  |
| 驗證     | ✗ 無    | ✓ 支援  |
| 流暢 API | ✓ 有    | △ 有限  |

## 內部實作細節

```php theme={null}
class Fluent
{
    protected $attributes = [];

    // 魔術方法：存取不存在的屬性
    public function __get($key)
    {
        return $this->value($key);
    }

    // 魔術方法：設定不存在的屬性
    public function __set($key, $value)
    {
        $this->offsetSet($key, $value);
    }

    // 魔術方法：呼叫不存在的方法
    // 方法名稱直接成為屬性 key
    public function __call($method, $parameters)
    {
        $this->attributes[$method] = count($parameters) > 0
            ? $parameters[0]
            : true;

        return $this;
    }
}
```

若未註冊 macro，`__call` 方法會將方法名稱作為屬性 key 為屬性設值，並回傳 `$this`。這使得方法鏈成為可能。

<Tip>
  Fluent 使用下列 trait，各自提供不同功能：

  * **Conditionable** — 以 `when()` / `unless()` 進行有條件的處理
  * **InteractsWithData** — `data()` 等資料操作方法
  * **Macroable** — 動態新增方法
</Tip>

## 下一步

<Card title="Collection 類別" icon="arrow-right-arrow-left" href="/zh-TW/advanced/collection-deep-dive">
  深入處理多元素的 Collection 類別。
</Card>

<Card title="Conditionable trait" icon="arrow-right-arrow-left" href="/zh-TW/advanced/conditionable">
  學習流暢寫出有條件處理的 Conditionable trait。
</Card>

<Card title="Macroable trait" icon="arrow-right-arrow-left" href="/zh-TW/advanced/macroable">
  學習為既有類別動態新增方法的 Macroable trait。
</Card>


## Related topics

- [tap() helper 與 Tappable trait](/zh-TW/advanced/tap.md)
- [字串操作（Str 類別）](/zh-TW/strings.md)
- [URL 生成](/zh-TW/urls.md)
- [InteractsWithData trait](/zh-TW/advanced/interacts-with-data.md)
- [自訂驗證規則](/zh-TW/advanced/custom-validation-rules.md)
