


Sharing examples of Laravel implementing user dynamic module development
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 事件产生时间
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 ...
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
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
Record dynamics
##
activity()->log('Look, I logged something');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'
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
$discussion = App\Discussion::create([...]); activity()->on($discussion) ->withProperty('event', 'discussion.created') ->log('发表了话题');Or when a user registers, I want to record an update:
activity()->on($user) ->withProperty('event', 'user.created') ->log('加入 EasyWeChat');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\ Activityuse 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);Then just traverse the display.
Some experience and skills
Set up a special dynamic observer class to record dynamics$ ./artisan make:listener UserActivitySubscriberThe code is as follows:
<?php namespace App\Listeners; class UserActivitySubscriber { protected $lisen = [ 'eloquent.created: App\User' => 'onUserCreated', 'eloquent.created: App\Discussion' => 'onDiscussionCreated', ]; public function subscribe($events) { foreach ($this->lisen as $event => $listener) { $events->lisen($event, __CLASS__.'@'.$listener); } } public function onUserCreated($user) { activity()->on($user) ->withProperty('event', 'user.created') ->log('加入 EasyWeChat'); } public function onDiscussionCreated($discussion) { activity()->on($discussion) ->withProperty('event', 'discussion.created')->log('发表了话题'); } }Then we register this subscription class: Register this in $subscribe in App\Providers\EventServiceProvider Subscription type:
/** * @var array */ protected $subscribe = [ \App\Listeners\UserActivitySubscriber::class, ];
上面我们利用了 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!

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version
