使用 whereInstanceOf 按类型过滤集合对象
Laravel 的 whereInstanceOf
方法提供了一个基于对象类型过滤集合的整洁方式,当使用多态关联或者混合类型对象集合时特别有用。
<?php
use App\Models\User;
use App\Models\Post;
use App\Models\Comment;
use Illuminate\Support\Collection;
$collection = collect([
new User(['name' => 'John']),
new Post(['title' => 'Hello']),
new User(['name' => 'Jane']),
]);
$users = $collection->whereInstanceOf(User::class);
让我们探讨一个处理具有不同类型活动的通知提要的实际示例:
<?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
{
// Get all activities
$activities = collect([
...$user->comments()->latest()->limit(5)->get(),
...$user->likes()->latest()->limit(5)->get(),
...$user->follows()->latest()->limit(5)->get(),
]);
// Sort all activities by created_at
$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
简化了集合中基于类型的过滤,使其更容易处理混合对象类型,同时保持代码整洁、可读。