Detailed laravel Development user Dynamic Module

Source: Internet
Author: User
Tags composer install
This article mainly introduces the user dynamic module development based on the laravel implementation of the relevant data, the text through the sample code introduced in very detailed, to everyone's study or work has a certain reference learning value, the need for friends below with the small series to learn together. We hope to help you.

Objective

As we all know, almost all Community applications have user dynamics This section, users can dynamically get more interesting content through friends, so as to improve community activity and user stickiness. Its implementation is relatively more complex than ordinary content publishing, mainly reflected in the content of diversity.

To solve this problem, we have to abstract these different types of content, extract the commonality, using the same structure to deal with, the development will be much simpler.

Concept Abstraction

User dynamics, as the name implies, dynamic generation, is a series of events history, so first of all to focus on the "event" the noun, it has what properties:

    • Trigger, community-based events are almost always triggered by the user

    • The event body, the subject information for the event, for example, "xxx published articles" in "articles".

    • Event properties, event bodies are different, and additional information is required, such as the event type.

    • The time that occurs, the time that the event is generated, of course, the time that all data is generated is usually recorded in our database.

It is easier to do this by abstracting the user dynamically into a structure with only 4 basic attributes:

-Description    Event description-causer_id or user_id event trigger-subject_id    body id-subject_type   Principal Type-    properties event attached Property- Created_at    Event Generation time

And the main part is Laravel morph relation, polymorphic Association.

How to show

Our dynamic presentation requirements typically include the following:

    • The News of my friends

    • A person's dynamics, usually a personal center

    • All dynamic, such as Laravel China home page of all the news

    • Dynamic search, relatively rare

I am recently developing easywechat new website, which also has user dynamics, for example:

XXX released a discussion "How do you use XXX" xxx commented on the topic of XXX "How do you use xxx" xxx replies to the comments of xxx "I am following the document ..." XXX purchased the "Development: custom menu use" xxx followed xxx ...

You will find that basically each dynamic is written differently, so we also need to record an "event type" such as "Focus", "release", "Reply", "buy".

Then we can use the blade or other template engine, switch ... case notation, to apply different templates to render these styles, such as blade, my usage:

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

Code implementation

Before we have discussed the data storage and display aspects of the design, and then how to achieve, if you are more diligent, can be native implementation, after all, the above implementation method has been described clearly, write code implementation is done, today I would like to recommend the use of spatie/ Laravel-activitylog to achieve:

The installation has always been simple, right:

$ composer Install SPATIE/LARAVEL-ACTIVITYLOG-VVV

Record dynamic

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

Of course, this kind of record doesn't make sense and there's hardly any useful information, so our usual usage should be 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 Description:

    • performedOn($model)Set the event body, which is the eloquent Model instance

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

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

    • withProperty($key, $value) Single use of event properties

    • log($description) Event description

For example, we want to record a message that the user has published a discussion about:

$discussion = App\discussion::create ([...]); Activity ()->on ($discussion)->withproperty (' event ', ' discussion.created ')->log (' published topic ');

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

Activity ()->on ($user)->withproperty (' event ', ' user.created ')->log (' Join Easywechat ');

You will find that I have not set the trigger, because this module if you do not set the trigger by default is the currently logged in user.

Show News

The presentation is based on conditions from the database, using the model classes provided by the package: spatie\activitylog\models\activity

Use spatie\activitylog\models\activity;

All dynamic $activities = Activity::all ();//dynamic $activities with user ID 2 = activity::causedby (User::find (2))->paginate (15);// Dynamic $activities with the article ID 13 as the main BODY = Activity::forsubject (post::find)->paginate (15);

Then it's good to traverse the display.

Some experience and skills

Set up a dedicated 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 ' =& Gt ' 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 (' Join Easywechat '),} public Function ondiscussioncreated ($discussion) {  activity ()->on ($ Discussion)    ->withproperty (' event ', ' discussion.created ')->log (' published topic ');}}

Then we go to register this subscription class:

Register this subscription class in the App\providers\eventserviceprovider $subscribe:

/** * @var array */protected $subscribe = [\app\listeners\useractivitysubscriber::class,];

Above we use the eloquent model event to monitor the change of the model, when the various model events are created, we call the corresponding method to record the dynamic, so it is very convenient to implement.

Record key information in event properties

When you see the above record dynamic, you may ask that only the ID is stored, this polymorphic association, the query will be very stressful, for example, we want to display the dynamic as:

Anchou published the article "Use of custom menus"

If we just store the ID and type of the article, we also need to query the article table, in order to get the title for display, such a dynamic list, it may be dozens of SQL, it is true, my solution is this:

In fact, our user dynamics is not required 100% accurate, so, I would like to record when the title of the article to save it is not necessary to check the table? In fact, the key information we need to present in the dynamic list, such as the title, is saved together with Withproperties so that a SQL solves the dynamic list problem.

Such practices also have drawbacks, such as the article changed the title, here is not synchronized, of course, you can also change this property in the article, but I personally think it is not much necessary. After all, the dynamic is the record of the situation, and then changed the title and there is no problem.

OK, the development of the user Dynamic module is shared here, if you have more advanced implementation welcome to communicate at any time.

About the friend dynamic part of the implementation, according to your application magnitude, as well as the storage of friends relationships are different, we can brainstorm, most of them are first to check the relationship between friends and then check the dynamic, related queries can also, their own implementation of it.

Related recommendations:

Detailed Laravel How to optimize the model query by pre-loading

Modify the root address of the URL () in Laravel

Detailed Laravel How to achieve timed tasks

Related Article

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.