jomisacu/ranking-generator

一个根据已知标准对项目进行排名的工具

dev-master 2023-03-02 13:41 UTC

This package is auto-updated.

Last update: 2024-09-30 01:36:28 UTC


README

创建排名的简单方法

什么是排名?

排名是根据某个方面的优劣来决定项目高低顺序的列表。例如,你可以有一系列视频摄像头型号,并按产生的视频质量进行排序。

不仅仅是按数字列表。根据多个方面有一般分类,例如,我们可以有一个分类叫做“2022年10款最佳智能手机”,排名的位置将由多个因素的组合决定。

安装

安装此软件包最简单的方法是使用composer

composer require jomisacu/ranking-generator

如何使用这个库?

使用此库有两种方法。首先,我们可以将我们的对象转换为“可排名”。也就是说,实现RankableItemInterface接口。这些对象可以用来创建Ranking类的实例,这就足够了。

为了帮助实现,我们添加了RankableItemTrait。让我们看看一个例子

<?php

use Jomisacu\RankingGenerator\Contracts\RankableItemInterface;
use Jomisacu\RankingGenerator\RankableItemTrait;

final class VideoCamera implements RankableItemInterface
{
    use RankableItemTrait;
    
    private int $pixels; // 1090
    private string $modelName; // Ej. 'Xiaomi camera xyz';

    public function __construct(string $modelName, int $pixels)
    {
        $this->modelName = $modelName;
        $this->pixels = $pixels;
    }

    public function getValue()
    {
        return $this->pixels;
    }

    protected function getUniqueDomainIdentifier(): string
    {
        return $this->modelName;
    }

    protected function computeRating(): \Jomisacu\RankingGenerator\Rating
    {
        $maxPixelsPossible = 4000;

        return new Rating($this->getValue() * 100 / $maxPixelsPossible); // ensures return a value between 1 and 100
    }
}

其次,使用排名生成器。在某些情况下,可能需要复杂的计算来生成排名。对于这些情况,我们提供了RankingGeneratorInterface合约,该合约提供了一个接收任意项目集合的build方法,并返回RankableItemInterface对象集合的方法。在这些情况下,使用RankingItem泛型类而不是修改我们的业务对象是完全有效的,这在需要基于相同项目进行多个排名时非常有用。

<?php

class MyRankingGenerator implements \Jomisacu\RankingGenerator\Contracts\RankingGeneratorInterface
{
    public function build(array $items) : array
    {
        $final = [];
        
        foreach ($items as $item) {
            $alreadyComputedRating = $this->someComplexLogic($item);
            
            $final[] = new \Jomisacu\RankingGenerator\RankingItem(
                $item['value_used_to_compute_the_rating'],
                $item['name_to_identify_the_item_in_the_context'],
                $alreadyComputedRating,
            );
        }  
        
        return $final;
    }  
        
    function someComplexLogic(array $item): \Jomisacu\RankingGenerator\Rating
    {
        // complex logic implementation
    }
}

RankingItem类非常简单。你可以根据输入生成评分,或者可以使用预先计算出的值。