首页 > 后端开发 > php教程 > 通过类型过滤收集对象,

通过类型过滤收集对象,

Karen Carpenter
发布: 2025-03-06 02:02:08
原创
314 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板