Sharing examples of Laravel implementing user dynamic module development

黄舟
Release: 2023-03-16 11:04:02
Original
1257 people have browsed it

This article mainly introduces you to the relevant information about the development of user dynamic modules based on Laravel. The article introduces it in great detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it Let’s learn with the editor below.

Preface

I believe everyone knows that almost all community applications have a user dynamics section, which users can obtain through friend dynamics More interesting content, thereby increasing community activity and user stickiness. Its implementation is relatively more complicated than ordinary content publishing, mainly reflected in the diversity of content.

In order to solve this problem, we have to abstract these different types of content, extract commonalities, and use the same structure to process them, which will make development much simpler.

Conceptual abstraction

User dynamics, as the name suggests, the generation of dynamics is the historical record of a series of events, so first focus on the "event" Noun, what attributes does it have:

  • Trigger, almost all events based on the community are triggered by users

  • Event subject, event The main information, such as "article" in "xxx published an article".

  • Event attributes, different event subjects require different additional information, such as event type.

  • Occurrence time records the time when the event occurs. Of course, our database usually records the time when all data is generated.

We abstract user dynamics into a structure with only 4 basic attributes, which is easier to implement:


- description    事件描述
- causer_id 或者 user_id 事件触发者
- subject_id    主体 ID
- subject_type   主体类型
- properties    事件附加属性
- created_at    事件产生时间
Copy after login

And the main body Part of it is morph relation in Laravel, polymorphic relation.

How to display

Our dynamic display needs usually include the following:

  • I The dynamics of friends

  • The dynamics of a certain person, usually the personal center

  • all the dynamics, such as all the dynamics on the Laravel China homepage

  • Dynamic search, relatively rare

I am currently developing a new version of EasyWeChat website, which also has user dynamics, for example:


xxx 发布了讨论 《请问大家怎么使用 xxx》
xxx 评论了 xxx 的话题 《请问大家怎么使用 xxx》
xxx 回复了 xxx 的评论 “我是按照文档上 ...”
xxx 购买了 《微信开发:自定义菜单的使用》
xxx 关注了 xxx
...
Copy after login

You will find that basically every dynamic is written differently, so we also need to record an "event type", such as "follow", "publish", "reply", and "purchase".

Then when we use blade or other template engines, we can switch... case writing to apply different templates to render these styles. For example, in blade, my usage is:


@switch($activity->properties['event'] ?? '')
 @case('discussion.created')
  ...
  @break
 @case('comment.created')
  ...
  @break
@endswitch
Copy after login

Code implementation

We have discussed the design of data storage and display before, and then how to implement it, if you It is relatively hard-working and can be implemented natively. After all, the above implementation method has been clearly described. Just write some code to implement it. What I would recommend today is to use spatie/laravel-activitylog to implement it:

Installation has always been very simple. Bar:


$ composer install spatie/laravel-activitylog -vvv
Copy after login

Record dynamics


##

activity()->log('Look, I logged something');
Copy after login

Of course this kind of record is meaningless, There is almost no useful information, so our usual usage should be like this:


activity()
 ->performedOn($anEloquentModel)
 ->causedBy($user)
 ->withProperties(['customProperty' => 'customValue'])
 ->log('Look, I logged something');
 
$lastLoggedActivity = Activity::all()->last();

$lastLoggedActivity->subject; //returns an instance of an eloquent model
$lastLoggedActivity->causer; //returns an instance of your user model
$lastLoggedActivity->getExtraProperty('customProperty'); //returns 'customValue'
$lastLoggedActivity->description; //returns 'Look, I logged something'
Copy after login

Method introduction:

  • performedOn($model) Set the event subject, which is the Eloquent Model instance

  • causedBy($user) Set the event trigger , User instance

  • withProperties($properties) The event properties in our concept above

  • withProperty( $key, $value) Single usage of event attributes

  • log($description) Event description

For example, we want to record a discussion when a user posts a discussion:


$discussion = App\Discussion::create([...]);

activity()->on($discussion)
->withProperty('event', 'discussion.created')
->log('发表了话题');
Copy after login

Or when a user registers, I want to record an update:


activity()->on($user)
->withProperty('event', 'user.created')
->log('加入 EasyWeChat');
Copy after login

You will find that I have not set the triggerer, because this module defaults to the currently logged in user if you do not set the triggerer.

Display dynamics

Display dynamics is to take them out from the database according to conditions. Here we use the model class provided by the package: Spatie\Activitylog\Models\ Activity

use Spatie\Activitylog\Models\Activity;


// 全部动态
$activities = Activity::all();
// 用户 ID 为 2 的动态 
$activities = Activity::causedBy(User::find(2))->paginate(15);
// 以文章 ID 为 13 为主体的动态
$activities = Activity::forSubject(Post::find(13))->paginate(15);
Copy after login

Then just traverse the display.

Some experience and skills

Set up a special dynamic observer class to record dynamics


$ ./artisan make:listener UserActivitySubscriber
Copy after login

The code is as follows:


<?php 

namespace App\Listeners;

class UserActivitySubscriber
{
 protected $lisen = [
  &#39;eloquent.created: App\User&#39; => &#39;onUserCreated&#39;,
  &#39;eloquent.created: App\Discussion&#39; => &#39;onDiscussionCreated&#39;,
 ];

 public function subscribe($events)
 {
  foreach ($this->lisen as $event => $listener) {
   $events->lisen($event, __CLASS__.&#39;@&#39;.$listener);
  }
 }

 public function onUserCreated($user)
 {
  activity()->on($user)
   ->withProperty(&#39;event&#39;, &#39;user.created&#39;)
   ->log(&#39;加入 EasyWeChat&#39;);
 }

 public function onDiscussionCreated($discussion)
 {
  activity()->on($discussion)
    ->withProperty(&#39;event&#39;, &#39;discussion.created&#39;)->log(&#39;发表了话题&#39;);
 }
}
Copy after login

Then we register this subscription class:

Register this in $subscribe in App\Providers\EventServiceProvider Subscription type:


/**
 * @var array
 */
protected $subscribe = [
 \App\Listeners\UserActivitySubscriber::class,
];
Copy after login

上面我们利用了 Eloquent 模型事件来监听模型的变化,当各种模型事件创建的时候我们调用对应的方法来记录动态,所以实现起来非常的方便。

在事件属性里记录关键信息

看到上面记录动态的时候你可能会问,只存储了 ID,这种多态关联,查询的时候会压力很大,比如,我们要将动态显示为:

安小超 发布了文章 《自定义菜单的使用》

我们如果只是存储了文章的 id 与类型,我们还需要查询一次文章表,才能得到标题用于显示,这样一个动态列表的话,可能会几十条 SQL 了,的确是这样的,我的解决方案是这样的:

其实我们的用户动态是不要求 100% 精准的,所以,我如果在记录时把文章的标题一起存下来是不是就不用再查表了?其实就是,我们在动态列表需要展示的关键信息,比如标题这些一起用 withProperties 存起来,这样就一条 SQL 解决了动态列表问题。

这样的做法也有弊端,比如文章改了标题的时候,这里就不同步了,当然你也可以在文章修改时来改这个属性,不过我个人认为没有多大必要。毕竟动态就是记录了当时的情况,后来改标题了并没有什么问题。

OK,用户动态模块的开发就分享到这里,如果你有更高级的实现欢迎随时交流。

关于好友动态部分的实现,根据你的应用量级,以及好友关系的存储各有不同,大家自己集思广益即可,大部分都是先查好友关系再查动态,关联查询也可以,自己实现吧。

总结

The above is the detailed content of Sharing examples of Laravel implementing user dynamic module development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template