承接 sunlab/wn-measures-plugin 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sunlab/wn-measures-plugin

Composer 安装命令:

composer require sunlab/wn-measures-plugin

包简介

Allows you to create/increment and display any measures you want on any model

README 文档

README

This plugin allows you to create, update and display any measures you want on a model, some examples could be:

  • Blog post's views
  • Number of forum topic creation from a member
  • Counting successive daily-connexion of a member
  • API's resource fetches count
  • ...

This plugin is intended to be used in more complex plugins or as is to register some statistics over your website's events.

Measurable Behavior

You can add the Measurable Behavior (think of it as a Trait) to any model you want. Using Storm Extension.

Extending existing models from a Plugin registration file:

Winter\Blog\Models\Post::extend(function ($postModel) {
    $postModel->implement[] = 'SunLab.Measures.Behaviors.Measurable';
});

Or directly to your Plugin's model:

class Link extends Model
{
    public $implement = ['SunLab.Measures.Behaviors.Measurable'];
    //...
}

[Experimental feature] Plugin's native and generic event listener

For the most basic events, you won't even need to write a line of code. This plugin creates a generic event listener which can handle the most basics use cases. Example here, it will listen for all the model.afterCreate event over the Winter\Forum\Models\Topic and increment a topic_created measure on the logged-in user. image

Create/Increment a measure

Once you've added the Measurable Behavior to a model, you can use the model's method incrementMeasure.

$post->incrementMeasure('views');

// Optional amount of incrementation can be passed
$post->incrementMeasure('views', 5);

Note: You don't have to process any kind of initialization of the measure, just use it.

Practical example 1, count how many times a user edit his posts

// In Plugin.php file
function boot()
{
    // Add the Measurable behavior to User model
    Winter\User\Models\User::extend(function($user) {
        // Verify it has not been already added by another plugin
        if (!$user->isClassExtendedWith('SunLab.Measures.Behaviors.Measurable')) {
            $user->extendClassWith('SunLab.Measures.Behaviors.Measurable');
        }
    });

    Winter\Forum\Models\Post::extend(function($post) {
        // Bind listener to update event
        $post->bindEvent('model.afterUpdate', function() use ($model) {
            // Increment measure on the member
            $post->member->incrementMeasure('post_edit');
        });
    });
}

Practical example 2, creating a post views in Winter.Blog:

title = "Blog post page"
url = "/blog/article/:slug"
layout = "default"
is_hidden = 0

[blogPost]
slug = "{{ :slug }}"
categoryPage = "blog/category"
==
function onEnd() {
    $this->blogPost->post->incrementMeasure('views');
}
==
{% component 'blogPost' %}

Bulk incrementation

You can increment multiple models measure at once, this is useful when you want to measure the amount of models fetches from an API.

To use Bulk incrementation, you need to pass a Builder instance of your query to the MeasureManager:

// Passing to the MeasureManager a Builder instance
$products = Product::where('name', 'like', '%shoes%');
MeasureManager::incrementMeasure($products, 'appearedInSearchResults');

return new JsonResponse([
    'products' => $products->get()
]);

Orphan measures

For some reason, you may want to increment some orphan measures:

    // Count how many users log-in
    Event::listen('winter.user.login', function() {
        MeasureManager::incrementOrphanMeasure('users_login');

        // incrementMeasure also support orphan measure.
        // Same as:
        MeasureManager::incrementMeasure('users_login');
    });

Decrement or reset a measure

The plugin support both decrement and reset on measures, related to model or orphan measure:

    // On model implementing Measurable
    $model->decrementMeasure('post_edit');
    $model->decrementMeasure('post_edit', 3); // An amount of decrementation can be passed

    // With orphan measures
    MeasureManager::decrementOrphanMeasure('users_login');
    MeasureManager::decrementOrphanMeasure('users_login', 3); // An amount of decrementation can be passed

Displaying a measure

To display the measure from a model, just use the getMeasure or getAmountOf methods on it. getMeasure returns a Measure model which contains an amount property

// From a backend controller/view
$post = Post::first();
$views = $post->getMeasure('views')->amount;
// Same as:
$views = $post->getAmountOf('views');
// From a frontend Twig block
{{ post.getMeasure('view').amount }}
// Same as:
{{ post.getAmountOf('view') }}

Events

As said earlier, this plugin gets really powerful and handy to use in other plugins. Events are fired on increment, decrement and reset measures. All the events contains the model (null for orphan measures), the measure object at its new state, and the amount. As an example, you can take a look into SunLab/Gamification for a full example:

// Plugin.php
Event::listen('sunlab.measures.incrementMeasure', function ($model, $measure) {
    // Filter the model we need
    if (!$model instanceof User) {
        return;
    }

    // Process some custom logic depending on the measure name and current amount
    // In that case, SunLab/Gamification assign "badges" depending on some measures incrementation
    $correspondingBadges =
        Badge::where([['measure_name', $measure->name], ['amount_needed', '<=', $measure->amount]])
            ->whereDoesntHave('users', function ($query) use ($model) {
                $query->where('user_id', $model->id);
            })->get();

    if (!blank($correspondingBadges)) {
        $now = now();
        $attachedBadges = array_combine(
            $correspondingBadges->pluck('id')->toArray(),
            array_fill(0, count($correspondingBadges), ['updated_at' => $now, 'created_at' => $now])
        );

        $model->badges()->attach($attachedBadges);
    }
});

MeasureManager and models

The MeasureManager static class handles orphan and bulk measures modification, but can also increment model measure:

// Using the MeasureManager static helpers:
use SunLab\Measures\Classes\MeasureManager;
    $post = \Winter\Blog\Models\Post::first();
    // Increment a model's measure
    MeasureManager::incrementMeasure($post, 'views');
    MeasureManager::incrementMeasure($post, 'views', 5);
    // Decrement:
    MeasureManager::decrementMeasure($model, 'views');
    MeasureManager::decrementMeasure($model, 'views', 3);
    // Reset
    MeasureManager::resetMeasure('views');
    MeasureManager::resetMeasure('views', 2);

TODO-List:

In a near future, I'll add some feature such as:

  • Bulk incrementation from a model collection instead of the Builder
  • A ReportWidget displaying some specific measures

sunlab/wn-measures-plugin 适用场景与选型建议

sunlab/wn-measures-plugin 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 89 次下载、GitHub Stars 达 2, 最近一次更新时间为 2021 年 05 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「plugin」 「emoji」 「winter」 「winter cms」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 sunlab/wn-measures-plugin 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 sunlab/wn-measures-plugin 我们能提供哪些服务?
定制开发 / 二次开发

基于 sunlab/wn-measures-plugin 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 89
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 11
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-05-03