看这个例子:
use App\Http\Resources\UserResource;
use App\Models\User;
Route::get('/user/{id}', function ($id) {
return new UserResource(User::findOrFail($id));
});
这在内部是如何工作的?因为乍一看我们只是返回一个类的对象UserResource
。但是 Laravel 神奇地调用了该toArray
函数并正确解析了它。
我希望我的推荐课程也能正常工作。
use App\Http\Recommendations\RecentlyUpdatedRecommendation;
use ...
Route::get('/someurl', function () {
return ['collections' => [
new RecentlyUpdatedRecommendation(),
new WatchlistRecommendation(),
new LastWatchedRecommendation(),
...
]];
});
和
/**
* All Recommendations use this as output
*/
abstract class Recommendation
{
// No Idea what needs to be put here
}
输出数组/json 应解析为:
return [
'title' => $title,
'description' => $description,
'courses' => (collection) $courses
];