首頁 >後端開發 >php教程 >通過類型過濾收集對象,

通過類型過濾收集對象,

Karen Carpenter
Karen Carpenter原創
2025-03-06 02:02:08315瀏覽

Filtering Collection Objects by Type with whereInstanceOf

Laravel的whereInstanceOf方法提供了一種簡潔的方式來根據對像類型過濾集合,這在處理多態關係或混合對象集合時特別有用。

以下是一個簡單的例子,展示如何使用whereInstanceOf過濾一個包含UserPost對象的集合:

<?php
use App\Models\User;
use App\Models\Post;
use Illuminate\Support\Collection;

$collection = collect([
    new User(['name' => 'John']),
    new Post(['title' => 'Hello']),
    new User(['name' => 'Jane']),
]);

$users = $collection->whereInstanceOf(User::class);

讓我們來看一個更實際的例子:處理包含不同類型活動的通知Feed。

<?php
namespace App\Services;

use App\Models\Comment;
use App\Models\Like;
use App\Models\Follow;
use Illuminate\Support\Collection;

class ActivityFeedService
{
    public function getUserFeed(User $user): array
    {
        // 获取所有活动
        $activities = collect([
            ...$user->comments()->latest()->limit(5)->get(),
            ...$user->likes()->latest()->limit(5)->get(),
            ...$user->follows()->latest()->limit(5)->get(),
        ]);
        // 按创建时间排序
        $activities = $activities->sortByDesc('created_at');

        return [
            'comments' => $activities->whereInstanceOf(Comment::class)
                ->map(fn (Comment $comment) => [
                    'type' => 'comment',
                    'text' => $comment->body,
                    'post_id' => $comment->post_id,
                    'created_at' => $comment->created_at
                ]),
            'likes' => $activities->whereInstanceOf(Like::class)
                ->map(fn (Like $like) => [
                    'type' => 'like',
                    'post_id' => $like->post_id,
                    'created_at' => $like->created_at
                ]),
            'follows' => $activities->whereInstanceOf(Follow::class)
                ->map(fn (Follow $follow) => [
                    'type' => 'follow',
                    'followed_user_id' => $follow->followed_id,
                    'created_at' => $follow->created_at
                ])
        ];
    }
}

whereInstanceOf簡化了集合中基於類型的過濾,使處理混合對像類型更容易,同時保持代碼簡潔易讀。

以上是通過類型過濾收集對象,的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn