marcanuy/popularity

该包最新版本(1.0.0)没有可用的许可信息。

Laravel 4 包,用于追踪网站在特定时间段内的热门元素

1.0.0 2014-02-06 20:09 UTC

This package is not auto-updated.

Last update: 2024-09-28 15:24:21 UTC


README

# Laravel 4 Popularity Package

Laravel 4 Popularity Package 会根据日期范围内的点击量跟踪您最热门的 Eloquent 模型,并允许您展示它们。

目录

特性

  • 追踪日期范围
    • 昨天
    • 过去7天
    • 过去30天
    • 所有时间
  • 可以同时追踪不同的模型,并选择显示哪个模型的热门项目

如何安装

设置

composer.json 文件的 require 键中添加以下内容

"marcanuy/popularity": "1.0.x"

运行 Composer 更新命令

$ composer update

在您的 config/app.php 中,将 'Marcanuy\Popularity\PopularityServiceProvider' 添加到 $providers 数组的末尾

'providers' => array(

    'Illuminate\Foundation\Providers\ArtisanServiceProvider',
    'Illuminate\Auth\AuthServiceProvider',
    ...
    'Marcanuy\Popularity\PopularityServiceProvider',

),

它还自动注册以下别名,使其在应用容器中可用

'aliases' => array(
    ..
    'Stats'      => 'Marcanuy\Popularity\Stats',
    'Popularity' => 'Marcanuy\Popularity\Facades\Popularity',
..
),

运行包迁移

生成包含每个 Eloquent 模型点击量的表

php artisan migrate --package=marcanuy/popularity

配置

对于您想要跟踪的每个 Eloquent 模型,您需要实现 src/models/PopularityInterface.php 接口,如下所示

#e.g. in models/ExamplePost.php

class ExamplePost implements \Marcanuy\Popularity\PopularityInterface
{
    public function popularityStats()
    {
        return $this->morphOne('Stats', 'trackable');
    }

    public function hit()
    {
        //check if a polymorphic relation can be set
        if($this->exists){
            $stats = $this->popularityStats()->first();
            if( empty( $stats ) ){
                //associates a new Stats instance for this instance
                $stats = new Stats();
                $this->popularityStats()->save($stats);
            }
            return $stats->updateStats();
        }
            return false;            
        }
    }

用法

它使用 Eloquent 的 多态关系,因此每个跟踪的模型都有自己的统计数据。

追踪点击量

对于已经保存到数据库中的每个模型实例(或已经有一个 ID),调用 hit() 方法来增加每个时间段的计数,例如在 routes.php 中,每次查看帖子或文章时,或者 Eloquent 事件被触发时。

Route::get('post/{id}', function($id)
{
    $post = ExamplePost::find($id);
    $post->hit();
    ...
}

检索最热门元素

默认情况下,它注册了 popularitypopularity/day 等路由,您可以在其中看到其用法的示例。它基于以下视图,可以轻松修改。

//copy package views into your app
php artisan view:publish marcanuy/popularity

您可以将这些视图作为子视图包含,或根据项目需求进行调整

app/views/packages/marcanuy/popularity/item_list.blade.php
app/views/packages/marcanuy/popularity/widget.blade.php

然后使用它们,例如

$items = Popularity::getStats('one_day_stats', 'DESC', '\Marcanuy\Popularity\ExamplePost')->paginate();
View::make('popularity::item_list')->with(array('items' => $items));

$topItems = Popularity::getStats('one_day_stats', 'DESC', '', 3)->get();
View::make('popularity::widget')->with(array('topItems' => $topItems));

许可

这是在 MIT 许可证条款下分发的免费软件

附加信息

WP-Most-Popular 启发并基于它构建

有任何问题,请发布 问题 或随时 联系我