I am trying to extend Kryptonit3/Counter. Particularly, I need to overwrite one private function inside the class Counter.php to retrieve only hits for the last 24 hours.
Counter.php private function:
private static function countHits($page)
{
$page_record = self::createPageIfNotPresent($page);
return number_format($page_record->visitors->count());
}
The function I need:
private static function countHits($page)
{
$page_record = self::createPageIfNotPresent($page);
return number_format($page_record->visitors()->where('created_at', '>=', Carbon::now()->subDay())->count());
}
Therefore, I am looking for the right way to overwrite this package.
Approach 1: Should I create my own class extending Counter.php and including my custom function in this class? If so, what happens with the private classes included in the original class? Should I create a service provider? How this service provider would look like?
Approach 2: Should I fork the vendor package and update this package to my own need?
I already looked at all stackoverflow questions related to this topic but they are not clear enough.
UPDATE: This is what I did so far:
Create MyCounter class:
<?php
namespace App\Helpers\Counter;
use Kryptonit3\Counter\Counter;
class MyCounter extends Counter
{
}
Create MyCounterServiceProvider:
<?php
namespace App\Providers;
use App\Helpers\MyCounter;
use Illuminate\Support\ServiceProvider;
class MyCounterServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app['counter'] = $this->app->share(function($app)
{
$visitor = $app['visitor'];
return new MyCounter($visitor);
});
}
}
Create MyCounterFacade:
<?php
namespace App\Helpers\Counter;
use Illuminate\Support\Facades\Facade;
class MyCounterFacade extends Facade
{
protected static function getFacadeAccessor() { return 'mycounter'; }
}
Include the provider and the alias inside config/app.php:
App\Providers\MyCounterServiceProvider::class,
and
'MyCounter' => App\Helpers\Counter\MyCounterFacade::class,
Problem was related with MyCounterServiceProvider. The next piece of code solved the problem.