在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):cyrildewit/eloquent-viewable开源软件地址(OpenSource Url):https://github.com/cyrildewit/eloquent-viewable开源编程语言(OpenSource Language):PHP 100.0%开源软件介绍(OpenSource Introduction):Eloquent ViewableThis Laravel >= 6.0 package allows you to associate views with Eloquent models. Once installed you can do stuff like this: // Return total views count
views($post)->count();
// Return total views count that have been made since 20 February 2017
views($post)->period(Period::since('2017-02-20'))->count();
// Return total views count that have been made between 2014 and 2016
views($post)->period(Period::create('2014', '2016'))->count();
// Return total unique views count (based on visitor cookie)
views($post)->unique()->count();
// Record a view
views($post)->record();
// Record a view with a cooldown
views($post)->cooldown(now()->addHours(2))->record(); OverviewSometimes you don't want to pull in a third-party service like Google Analytics to track your application's page views. Then this package comes in handy. Eloquent Viewable allows you to easiliy associate views with Eloquent models. It's designed with simplicity in mind. This package stores each view record individually in the database. The advantage of this is that it allows us to make very specific counts. For example, if we want to know how many people has viewed a specific post between January 10 and February 17 in 2018, we can do the following: FeaturesHere are some of the main features:
DocumentationIn this documentation, you will find some helpful information about the use of this Laravel package. Table of contents
Getting StartedRequirementsThis package requires PHP 7.4+ and Laravel 6+. Support for Lumen is not maintained! Version information
InstallationFirst, you need to install the package via Composer: composer require cyrildewit/eloquent-viewable Secondly, you can publish the migrations with: php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="migrations" Finally, you need to run the php artisan migrate You can optionally publish the config file with: php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="config" Register service provider manuallyIf you prefer to register packages manually, you can add the following provider to your application's providers list. // config/app.php
'providers' => [
// ...
CyrildeWit\EloquentViewable\EloquentViewableServiceProvider::class,
]; UsagePreparing your modelTo associate views with a model, the model must implement the following interface and trait:
Example: use Illuminate\Database\Eloquent\Model;
use CyrildeWit\EloquentViewable\InteractsWithViews;
use CyrildeWit\EloquentViewable\Contracts\Viewable;
class Post extends Model implements Viewable
{
use InteractsWithViews;
// ...
} Recording viewsTo make a view record, you can call the views($post)->record(); The best place where you should record a visitors's view would be inside your controller. For example: // PostController.php
public function show(Post $post)
{
views($post)->record();
return view('post.show', compact('post'));
} Note: This package filters out crawlers by default. Be aware of this when testing, because Postman is for example also a crawler. Setting a cooldownYou may use the views($post)
->cooldown($minutes)
->record(); Instead of passing the number of minutes as an integer, you can also pass a $expiresAt = now()->addHours(3);
views($post)
->cooldown($expiresAt)
->record(); How it worksWhen recording a view with a session delay, this package will also save a snapshot of the view in the visitor's session with an expiration datetime. Whenever the visitor views the item again, this package will checks his session and decide if the view should be saved in the database or not. Retrieving views countsGet total views countviews($post)->count(); Get views count of a specific perioduse CyrildeWit\EloquentViewable\Support\Period;
// Example: get views count from 2017 upto 2018
views($post)
->period(Period::create('2017', '2018'))
->count(); The Between two datetimes$startDateTime = Carbon::createFromDate(2017, 4, 12);
$endDateTime = '2017-06-12';
Period::create($startDateTime, $endDateTime); Since a datetimePeriod::since(Carbon::create(2017)); Upto a datetimePeriod::upto(Carbon::createFromDate(2018, 6, 1)); Since pastUses Period::pastDays(int $days);
Period::pastWeeks(int $weeks);
Period::pastMonths(int $months);
Period::pastYears(int $years); Since subUses Period::subSeconds(int $seconds);
Period::subMinutes(int $minutes);
Period::subHours(int $hours);
Period::subDays(int $days);
Period::subWeeks(int $weeks);
Period::subMonths(int $months);
Period::subYears(int $years); Get total unique views countIf you only want to retrieve the unique views count, you can simply add the views($post)
->unique()
->count(); Order models by views countThe Order by views countPost::orderByViews()->get(); // descending
Post::orderByViews('asc')->get(); // ascending Order by unique views countPost::orderByUniqueViews()->get(); // descending
Post::orderByUniqueViews('asc')->get(); // ascending Order by views count within the specified periodPost::orderByViews('asc', Period::pastDays(3))->get(); // descending
Post::orderByViews('desc', Period::pastDays(3))->get(); // ascending And of course, it's also possible with the unique views variant: Post::orderByUniqueViews('asc', Period::pastDays(3))->get(); // descending
Post::orderByUniqueViews('desc', Period::pastDays(3))->get(); // ascending Order by views count within the specified collectionPost::orderByViews('asc', null, 'custom-collection')->get(); // descending
Post::orderByViews('desc', null, 'custom-collection')->get(); // ascending
Post::orderByUniqueViews('asc', null, 'custom-collection')->get(); // descending
Post::orderByUniqueViews('desc', null, 'custom-collection')->get(); // ascending Get views count of viewable typeIf you want to know how many views a specific viewable type has, you need to pass an empty Eloquent model to the views(new Post())->count(); You can also pass a fully qualified class name. The package will then resolve an instance from the application container. views(Post::class)->count();
views('App\Post')->count(); View collectionsIf you have different types of views for the same viewable type, you may want to store them in their own collection. views($post)
->collection('customCollection')
->record(); To retrieve the views count in a specific collection, you can reuse the same views($post)
->collection('customCollection')
->count(); Remove views on deleteTo automatically delete all views of an viewable Eloquent model on delete, you can enable it by setting the protected $removeViewsOnDelete = true; Caching view countsCaching the views count can be challenging in some scenarios. The period can be for example dynamic which makes caching not possible. That's why you can make use of the in-built caching functionality. To cache the views count, simply add the Examples: views($post)->remember()->count();
views($post)->period(Period::create('2018-01-24', '2018-05-22'))->remember()->count();
views($post)->period(Period::upto('2018-11-10'))->unique()->remember()->count();
views($post)->period(Period::pastMonths(2))->remember()->count();
views($post)->period(Period::subHours(6))->remember()->count(); // Cache for 3600 seconds
views($post)->remember(3600)->count();
// Cache until the defined DateTime
views($post)->remember(now()->addWeeks(2))->count();
// Cache forever
views($post)->remember()->count(); OptimizingBenchmarksDatabase indexesThe default If you have enough storage available, you can add another index for the CachingCaching views counts can have a big impact on the performance of your application. You can read the documentation about caching the views count here Using the Example: we want to order our blog posts by unique views count. The first thing that may come to your mind is to use the $posts = Post::latest()->orderByUniqueViews()->paginate(20); This query is quite slow when you have a lot of views stored. To speed things up, you can add for example a There may be a faster way to do this, but such command can be like: $posts = Post::all();
foreach($posts as $post) {
$post->unique_views_count = views($post)->unique()->count();
} To be updated! Laravel has a nice chunk and cursor feature what may come in handy. ExtendingIf you want to extend or replace one of the core classes with your own implementations, you can override them:
Note: Don't forget that all custom classes must implement their original interfaces Custom information about visitorThe
The default You can override the
Create your own |