


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');
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('发表了话题');
activity()->on($user) ->withProperty('event', 'user.created') ->log('加入 EasyWeChat');
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);
Some experience and skills
Set up a special dynamic observer class to record dynamics$ ./artisan make:listener UserActivitySubscriber
<?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('发表了话题'); } }
/** * @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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

PHP Unit and Integration Testing Guide Unit Testing: Focus on a single unit of code or function and use PHPUnit to create test case classes for verification. Integration testing: Pay attention to how multiple code units work together, and use PHPUnit's setUp() and tearDown() methods to set up and clean up the test environment. Practical case: Use PHPUnit to perform unit and integration testing in Laravel applications, including creating databases, starting servers, and writing test code.

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.
