如何从多个对象构建流/源?(How can I build a stream/feed from multiple objects?)

编程入门 行业动态 更新时间:2024-10-27 12:24:26
如何从多个对象构建流/源?(How can I build a stream/feed from multiple objects?)

我想在应用程序的首页上构建通知流。 现在,我有新闻,会议和演示的模型。 我想将这些元素组合成一个对象,可能称为事件,这样我就可以获取最新的5个事件并在首页上显示它们。 输出将是这样的:

News Article: Submissions open starting April 1 Presentatiion: How to do stuff, the PDF Meeting: April 15, Foo High School Gymnasium

这些对象都实现了一个需要getTitle,getBody和getCreationDate的接口,因此每个对象都可以使用这些函数。

我不想简单地合并集合,因为它变得混乱。 有没有办法将这些对象组合成一个对象?

I want to build a notification stream on the front page of an application. Right now, I have models for News, Meetings, and Presentations. I want to combine these elements into a single object, perhaps called Events, so that I can then take the most recent 5 Events and display them on the front page. The output would be something like:

News Article: Submissions open starting April 1 Presentatiion: How to do stuff, the PDF Meeting: April 15, Foo High School Gymnasium

The objects all implement an interface which requires getTitle, getBody and getCreationDate, so these functions are available to each object.

I don't want to simply merge the collections, as that gets messy. Is there any way to combine these objects into a single object?

最满意答案

似乎是继承的经典案例。 您可以创建一个名为Event的模型。

class Event extends Model

然后你提到的类将扩展事件。

class Article extends Event class Presentation extends Event class Meeting extends Event

然后你可以在Event类上创建一个自定义方法。 我认为如果你想避免合并集合,那么在你的情况下编写简单的SQL比使用Eloquent更简单。

public function getUpcomingEvents() { // something like that, you get the idea return DB::select(' (SELECT title, body, CreationDate FROM articles LIMIT 5) UNION (SELECT title, body, CreationDate FROM meetings LIMIT 5) ORDER BY CreationDate DESC LIMIT 5')->get(); }

这将使您的控制器保持干净和漂亮,模型结构将代表底层逻辑。

Seems like a classic case for inheritance. You can create a model called Event.

class Event extends Model

Then your mentioned classes would extend the Event.

class Article extends Event class Presentation extends Event class Meeting extends Event

Then you could make a custom method on Event class. I think it would be simpler to write straightforward SQL than mess with Eloquent in your case, if you wish to avoid merging collections.

public function getUpcomingEvents() { // something like that, you get the idea return DB::select(' (SELECT title, body, CreationDate FROM articles LIMIT 5) UNION (SELECT title, body, CreationDate FROM meetings LIMIT 5) ORDER BY CreationDate DESC LIMIT 5')->get(); }

This would keep your controllers clean and nice and models structure would represent the underlying logic.

更多推荐

本文发布于:2023-07-24 00:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239325.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   对象   build   stream   multiple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!