翻译进度
21
分块数量
6
参与人数

定义 Metrics

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


Nova 的 metrics 可以帮助您快速了解应用的关键业务指标。例如,您可以定义一个 metrics,用来显示每天添加到应用中的用户总数或每周销售额。

Nova 提供三种类型的内置 metrics:值 metrics、趋势 metrics和分区 metrics。下面我们将学习每种类型的 metrics 并在演示它们的用法。

yuanjw 翻译于 1年前

Value Metrics

Value metrics 可以展示单个值,如果需要, 也可以显示与上个周期间隔的比值。 例如,一个 value metric 想显示前三十天新用户和 上个三十天新用户的比值:

Value Metric

Value metrics 可以使用 nova:value Artisan 命令生成. 默认 所有新生成的 metrics 都会在 app/Nova/Metrics 目录中:

php artisan nova:value NewUsers
skies 翻译于 1年前

一旦生成值 metric 类后,您就可以对其进行自定义了。每个值 metric 都有一个 calculate 方法,该方法返回了一个Laravel\Nova\Metrics\ValueResult 对象。Nova 附带了各种帮助程序,可以快速生成结果。

下面的例子,我们使用 count 助手自动对选定范围的 Eloquent 模型执行 count 查询,并自动对“上一个”索引范围计数。

<?php

namespace App\Nova\Metrics;

use App\User;
use Illuminate\Http\Request;
use Laravel\Nova\Metrics\Value;

class NewUsers extends Value
{
    /**
     * 计算 metric 的值。
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function calculate(Request $request)
    {
        return $this->count($request, User::class);
    }

    /**
     * 获取 metric 的时间范围。
     *
     * @return array
     */
    public function ranges()
    {
        return [
            30 => '30 Days',
            60 => '60 Days',
            365 => '365 Days',
            'MTD' => 'Month To Date',
            'QTD' => 'Quarter To Date',
            'YTD' => 'Year To Date',
        ];
    }

    /**
     * 获取 metric 的 URI 键。
     *
     * @return string
     */
    public function uriKey()
    {
        return 'new-users';
    }
}
chuse 翻译于 1周前

值查询类型

值 metrics 不只是附带一个 count 助手。在构建 metric 时,您还可以在构建 metric 时使用各种其他聚合函数。

Average

average 方法可用于计算给定列与前一个时间间隔/范围相比的平均值:

return $this->average($request, Post::class, 'word_count');
laradocs 翻译于 1周前

Sum

The sum method may be used to calculate the sum of a given column compared to the previous time interval / range:

return $this->sum($request, Order::class, 'price');

Max

The max method may be used to calculate the maximum of a given column compared to the previous time interval / range:

return $this->max($request, Order::class, 'total');

Min

The min method may be used to calculate the minimum of a given column compared to the previous time interval / range:

return $this->min($request, Order::class, 'total');

Value Ranges

Every value metric class contains a ranges method. This method determines the ranges that will be available in the value metric's range selection menu. The array's keys determine the number of days that should be included in the query, while the values determine the "human readable" text that will be placed in the range selection menu. Of course, you are not required to define any ranges at all:

/**
 * Get the ranges available for the metric.
 *
 * @return array
 */
public function ranges()
{
    return [
        5 => '5 Days',
        10 => '10 Days',
        15 => '15 Days',
        'MTD' => 'Month To Date',
        'QTD' => 'Quarter To Date',
        'YTD' => 'Year To Date',
    ];
}

MTD / QTD / YTD Range Keys

You may customize these ranges to suit your needs; however, if you are using the built-in "Month To Date", "Quarter To Date", or "Year To Date" ranges, you should not change their keys.

手动构建结果值

如果你不能使用自带的查询助手构建您的 metric 值,你可以使用 resultprevious 方法手动为 metric 提供最终值:

return $this->result(100)->previous(50);

趋势 Metrics

趋势 metrics 通过折线图显示随着时间变化的值。例如,趋势 metric 可能会显示过去 30 天内每天创建的新用户数:

Trend Metric

laradocs 翻译于 1周前

Trend metrics may be generated using the nova:trend Artisan command. By default, all new metrics will be placed in the app/Nova/Metrics directory:

php artisan nova:trend UsersPerDay

Once your trend metric class has been generated, you're ready to customize it. Each trend metric class contains a calculate method. This method should return a Laravel\Nova\Metrics\TrendResult object. Don't worry, Nova ships with a variety of helpers for quickly generating results.

In this example, we are using the countByDays helper, which will automatically perform a count query against the specified Eloquent model for the selected range and for the selected interval unit (in this case, days):

<?php

namespace App\Nova\Metrics;

use App\User;
use Illuminate\Http\Request;
use Laravel\Nova\Metrics\Trend;

class UsersPerDay extends Trend
{
    /**
     * Calculate the value of the metric.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function calculate(Request $request)
    {
        return $this->countByDays($request, User::class);
    }

    /**
     * Get the ranges available for the metric.
     *
     * @return array
     */
    public function ranges()
    {
        return [
            30 => '30 Days',
            60 => '60 Days',
            90 => '90 Days',
        ];
    }

    /**
     * Get the URI key for the metric.
     *
     * @return string
     */
    public function uriKey()
    {
        return 'users-per-day';
    }
}

趋势查询类型

趋势 metrics 不只是附带一个 countByDays 助手。在构建 metric 时,您还可以使用各种其他聚合函数和时间间隔。

Count

count 方法可用于计算给定列随着时间变化的计数:

return $this->countByMonths($request, User::class);
return $this->countByWeeks($request, User::class);
return $this->countByDays($request, User::class);
return $this->countByHours($request, User::class);
return $this->countByMinutes($request, User::class);
laradocs 翻译于 1周前

Average

average 方法可用于计算给定列随着时间变化的平均值:

return $this->averageByMonths($request, Post::class, 'word_count');
return $this->averageByWeeks($request, Post::class, 'word_count');
return $this->averageByDays($request, Post::class, 'word_count');
return $this->averageByHours($request, Post::class, 'word_count');
return $this->averageByMinutes($request, Post::class, 'word_count');

Sum

sum 方法可用于计算给定列随着时间变化的总和:

return $this->sumByMonths($request, Order::class, 'price');
return $this->sumByWeeks($request, Order::class, 'price');
return $this->sumByDays($request, Order::class, 'price');
return $this->sumByHours($request, Order::class, 'price');
return $this->sumByMinutes($request, Order::class, 'price');
laradocs 翻译于 1周前

Max

max 方法可用于计算给定列随着时间变化的最大值:

return $this->maxByMonths($request, Order::class, 'total');
return $this->maxByWeeks($request, Order::class, 'total');
return $this->maxByDays($request, Order::class, 'total');
return $this->maxByHours($request, Order::class, 'total');
return $this->maxByMinutes($request, Order::class, 'total');

Min

min 方法可用于计算给定列随着时间变化的最小值:

return $this->minByMonths($request, Order::class, 'total');
return $this->minByWeeks($request, Order::class, 'total');
return $this->minByDays($request, Order::class, 'total');
return $this->minByHours($request, Order::class, 'total');
return $this->minByMinutes($request, Order::class, 'total');
laradocs 翻译于 1周前

Trend Ranges

Every trend metric class contains a ranges method. This method determines the ranges that will be available in the trend metric's range selection menu. The array's keys determine the number of time interval units (months, weeks, days, etc.) that should be included in the query, while the values determine the "human readable" text that will be placed in the range selection menu. Of course, you are not required to define any ranges at all:

/**
 * Get the ranges available for the metric.
 *
 * @return array
 */
public function ranges()
{
    return [
        5 => '5 Days',
        10 => '10 Days',
        15 => '15 Days',
    ];
}

格式化趋势值

有时,您可能希望添加一个前缀或后缀到趋势值。为了实现这一点,您可以使用 prefixsuffix 方法:

return $this->countByDays($request, User::class)
            ->prefix('$');

如果你的趋势 metric 是显示一个货币值,您可以使用 dollarseuros 快捷方法快速在趋势值前添加美元或欧元符号:

return $this->countByDays($request, User::class)
            ->dollars();
laradocs 翻译于 1周前

显示当前值

有时,您可能希望突出最新时间间隔的值。例如,在这个截图中,在最后一天创建了 6 个用户:

Latest Value

您可以使用 showLatestValue 方法完成这个:

return $this->countByDays($request, User::class)
            ->showLatestValue();
laradocs 翻译于 1周前

Manually Building Trend Results

If you are not able to use the included query helpers for building your trend metric, you may manually construct the Laravel\Nova\Metrics\TrendResult object and return it from your metric's calculate method:

return (new TrendResult)->trend([
    'July 1' => 100,
    'July 2' => 150,
    'July 3' => 200,
]);

Partition Metrics

Partition metrics displays a pie chart of values. For example, a partition metric might display the total number of users for each billing plan offered by your application:

Partition Metric

Partition metrics may be generated using the nova:partition Artisan command. By default, all new metrics will be placed in the app/Nova/Metrics directory:

php artisan nova:partition UsersPerPlan

Once your partition metric class has been generated, you're ready to customize it. Each partition metric class contains a calculate method. This method should return a Laravel\Nova\Metrics\PartitionResult object. Don't worry, Nova ships with a variety of helpers for quickly generating results.

In this example, we are using the count helper, which will automatically perform a count query against the specified Eloquent model and retrieve the number of models belonging to each distinct value of your specified "group by" column:

<?php

namespace App\Nova\Metrics;

use App\User;
use Illuminate\Http\Request;
use Laravel\Nova\Metrics\Partition;

class UsersPerPlan extends Partition
{
    /**
     * Calculate the value of the metric.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function calculate(Request $request)
    {
        return $this->count($request, User::class, 'stripe_plan');
    }

    /**
     * Get the URI key for the metric.
     *
     * @return string
     */
    public function uriKey()
    {
        return 'users-by-plan';
    }
}

Partition Query Types

Partition metrics don't just ship with a count helper. You may also use a variety of other aggregate functions when building your metric.

Average

The average method may be used to calculate the average of a given column within distinct groups. For example, the following call to the average method will display a pie chart with the average order price for each department of the company:

return $this->average($request, Order::class, 'price', 'department');

Sum

The sum method may be used to calculate the sum of a given column within distinct groups. For example, the following call to the sum method will display a pie chart with the sum of all order prices for each department of the company:

return $this->sum($request, Order::class, 'price', 'department');

Max

The max method may be used to calculate the max of a given column within distinct groups. For example, the following call to the max method will display a pie chart with the maximum order price for each department of the company:

return $this->max($request, Order::class, 'price', 'department');

Min

min 方法可用于计算不同组内给定列的最小值。例如下面的 min 方法将显示一个饼图,其中包含公司每个部门的最低订单价格:

return $this->min($request, Order::class, 'price', 'department');

自定义分区标签

通常,将分区 metrics 指标分组的列值将是最简单的键,而不是 “友好” 的东西。或者,如果您要显示布尔值列分组的分区 metric,Nova 会将您的组标签显示为 “0” 和 "1"。因此,Nova 允许您提供一个 Closure 将标签格式化为更具有可读性的内容:

/**
 * 计算 metric 的值。
 *
 * @param  \Illuminate\Http\Request  $request
 * @return mixed
 */
public function calculate(Request $request)
{
    return $this->count($request, User::class, 'stripe_plan')
            ->label(function ($value) {
                switch ($value) {
                    case null:
                        return 'None';
                    default:
                        return ucfirst($value);
                }
            });
}
laradocs 翻译于 1周前

手动生成分区结果

如果您无法使用内置的查询助手构建你的分区 metric,您可以使用 result 方法手动为 metric 提供最终值:

return $this->result([
    'Group 1' => 100,
    'Group 2' => 200,
    'Group 3' => 300,
]);
laradocs 翻译于 1周前

缓存

有时 metric 值的计算可能会很慢且成本很高。因此,所有 Nova metrics 都包含一个 cacheFor 方法,该方法允许您指定 metric 结果的缓存时长:

/**
 * 指定 metric 应缓存多少分钟。
 *
 * @return  \DateTimeInterface|\DateInterval|float|int
 */
public function cacheFor()
{
    return now()->addMinutes(5);
}
laradocs 翻译于 1周前

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
贡献者:6
讨论数量: 0
发起讨论 只看当前版本


暂无话题~