User dynamic module development based on Laravel, laravel Module

Source: Internet
Author: User
Tags composer install

User dynamic module development based on Laravel, laravel Module

Preface

As we all know, almost all Community applications have user dynamics. Users can use friends to obtain more content they are interested in, thus improving community activity and user stickiness. Its implementation is relatively more complex than normal content publishing, mainly reflected in the content diversity.

To solve this problem, we need to abstract these different types of content, extract commonalities, and use the same structure for processing. It will be much simpler to develop.

Concept Abstraction

User dynamics, as its name implies, are the historical records of a series of events. Therefore, we should first focus on the term "events" and what attributes it has:

  • Trigger: almost all events in the Community are triggered by users.
  • The subject of the event, such as the article published in "xxx ".
  • The event attributes and the event subject are different, and the additional information required is also different, such as the event type.
  • The occurrence time records the time when an event is generated. Of course, the time when all data is generated in our database is recorded.

We can dynamically abstract users into a structure with only four basic attributes, which is easier to implement:

-Description event description-causer_id or user_id event trigger-subject_id subject ID-subject_type subject type-properties event additional property-created_at event generation time

The main part is the morph relation in Laravel, which is a multi-state association.

How to display

Our dynamic presentation requirements usually include the following:

  • My friends
  • The dynamics of a person, usually the personal Center
  • All updates, such as all updates on the Laravel China Homepage
  • Dynamic search, rare

I recently developed a new version of EasyWeChat website, which also contains user dynamics. For example:

Xxx posted a discussion about "how do you use xxx" xxx commented on xxx's topic "how do you use xxx?" xxx replied to xxx's comment "I followed the document... "xxx purchased" Development: Use of custom menu "xxx followed xxx...

You will find that basically every kind of dynamic writing method is different, so we need to record an "Event Type ", for example, "Follow", "publish", "reply", and "purchase ".

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

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

Code Implementation

We have discussed the design of data storage and presentation, and then how to implement it. If you are hardworking, You can implement it in native mode. After all, the above implementation method has been clearly described, you can implement the Code by writing it. Today, we recommend that you use spatie/laravel-activitylog to implement it:

Installation has always been simple, right:

$ composer install spatie/laravel-activitylog -vvv

Record Dynamics

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

Of course, this record is meaningless and there is almost no useful information, so our common usage should be as follows:

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, that is, the Eloquent Model instance.
  • causedBy($user)Set the event trigger, User instance
  • withProperties($properties)Event attributes in our concepts above
  • withProperty($key, $value) Single usage of event attributes
  • log($description) Event Description

For example, we need to record one and the user has published a discussion:

$ Discussion = App \ Discussion: create ([...]); activity ()-> on ($ discussion)-> withProperty ('event', 'discussion. created ')-> log ('posted topic ');

Or when a user registers, I want to record a dynamic record:

Activity ()-> on ($ user)-> withProperty ('event', 'user. created ')-> log ('add easychat ');

You will find that I have not set a trigger, because if you do not set a trigger in this module, it is the current login user by default.

Dynamic Display

Dynamic Display is taken out of the database based on conditions. The model class provided by the package is used here: Spatie \ Activitylog \ Models \ Activity.

Use Spatie \ Activitylog \ Models \ Activity;

// All dynamic $ activities = Activity: all (); // dynamic $ activities = Activity: causedBy (User: find (2) with User ID 2 )) -> paginate (15); // dynamic content with the Article ID as 13 $ activities = Activity: forSubject (Post: find (13 )) -> paginate (15 );

The next step is to traverse the display.

Experience and skills

Set a special dynamic observer class to record the dynamic

$ ./artisan make:listener UserActivitySubscriber

The 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 (' add EasyWeChat ');} public function onDiscussionCreated ($ discussion) {activity ()-> on ($ discussion)-> withProperty ('event ', 'discussion. created ')-> log ('posted topic ');}}

Then we will register this subscription class:

Register this subscription class in $ subscribe in App \ Providers \ EventServiceProvider:

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

We have used the Eloquent model event to listen for model changes. When various model events are created, we call the corresponding method to record the dynamics, so it is very convenient to implement.

Record key information in event Properties

When you see the above record dynamics, you may ask, only store the ID, this kind of multi-State Association, the query will be a lot of pressure, for example, we want to dynamically display:

An Xiaochao published the article "use of custom Menus"

If we only store the Article id and type, we also need to query the article table to obtain the title for display. If such a dynamic list is used, it may take dozens of SQL statements, indeed, my solution is as follows:

In fact, our user dynamics do not require 100% accuracy. Therefore, if I save the title of the article together during the record, do I have to look up the table again? In fact, we need to display the key information in the dynamic list, such as the title, which is stored together with withProperties, so that an SQL statement solves the dynamic list problem.

This method also has drawbacks. For example, when the title of an article is changed, it will not be synchronized here. Of course, you can modify this attribute during the article, but I personally think it is not necessary. After all, the dynamics record the current situation, and there is no problem after the title is changed.

OK. Let's share the development of the user's dynamic module here. If you have more advanced implementations, feel free to contact us.

The implementation of the "friend Dynamics" section varies depending on the application level and the storage of friend relationships. You can brainstorm on your own. Most of the operations are based on checking the friend relationship and then querying the dynamics. You can also query the association, implement it by yourself.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.