0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

メソッドチェーンとは?

Posted at

メソッドチェーンとは?

メソッドチェーン(Method Chaining) とは、
オブジェクト指向プログラミングで 複数のメソッドを連続して呼び出す 書き方のことです。
LaravelのCollectionでは、メソッドチェーンを活用することで、コードをシンプルかつ可読性の高いものにできます。

メソッドチェーンの基本

通常、複数の処理をするときは変数に代入しながら書くことが多いです。

例:通常の配列操作

$numbers = [1, 2, 3, 4, 5];

// ① 2倍にする
$doubled = array_map(function ($num) {
    return $num * 2;
}, $numbers);

// ② 偶数のみを取得
$filtered = array_filter($doubled, function ($num) {
    return $num % 2 === 0;
});

// ③ インデックスをリセット
$final = array_values($filtered);

print_r($final); // [2, 4, 6, 8, 10]

▶ 問題点

  • doubled, filtered, final の中間変数が増えるため、コードが長くなりがち。

Collectionでのメソッドチェーン

$final = collect([1, 2, 3, 4, 5])
    ->map(fn($num) => $num * 2)  // ① 2倍にする
    ->filter(fn($num) => $num % 2 === 0) // ② 偶数のみ取得
    ->values(); // ③ インデックスをリセット

print_r($final->all()); // [2, 4, 6, 8, 10]

▶ メリット

  • 中間変数が不要になり、コードがスッキリする。
  • 処理の流れが直感的に理解しやすい。
  • 無駄な配列操作が減るため、パフォーマンスが向上する。

メソッドチェーンの活用例

ユーザー情報の処理について

例えば、以下のようなデータがあるとする。

$users = collect([
    ['id' => 1, 'name' => 'Alice', 'age' => 25],
    ['id' => 2, 'name' => 'Bob', 'age' => 17],
    ['id' => 3, 'name' => 'Charlie', 'age' => 30],
]);

このデータから 年齢20歳以上のユーザー名を取得するとする

メソッドチェーンを使った場合
$adultNames = $users
    ->filter(fn($user) => $user['age'] >= 20) // ① 20歳以上にフィルタ
    ->map(fn($user) => $user['name']) // ② 名前だけ取得
    ->values(); // ③ インデックスをリセット

print_r($adultNames->all()); // ['Alice', 'Charlie']
通常の配列を使った場合
$filtered = array_filter($users, function ($user) {
    return $user['age'] >= 20;
});

$names = array_map(function ($user) {
    return $user['name'];
}, $filtered);

$final = array_values($names);

print_r($final); // ['Alice', 'Charlie']

▶ Collectionを使うと 簡潔 になるのが分かる!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?