PHP code example of zfhassaan / genlytics
1. Go to this page and download the library: Download zfhassaan/genlytics library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
zfhassaan / genlytics example snippets
'providers' => [
// ...
zfhassaan\genlytics\provider\AnalyticsServiceProvider::class,
],
'aliases' => [
// ...
'Genlytics' => zfhassaan\genlytics\facades\AnalyticsFacade::class,
],
use zfhassaan\genlytics\facades\AnalyticsFacade as Genlytics;
// 1. Fluent queries with pre-defined date macros
$data = Genlytics::query()
->last7Days()
->dimensions(['country', 'city'])
->metrics(['activeUsers', 'sessions'])
->orderByDesc('activeUsers')
->limit(10)
->remember(3600) // Cache query for 1 hour
->get();
// 2. Direct Strongly-Typed DTO Casting
$pageDtos = Genlytics::query()->last30Days()->toPageDto();
foreach ($pageDtos as $page) {
echo "{$page->path}: {$page->views} views
";
}
// 3. Direct Standardized Laravel API Resource Casting (with SemVer envelope)
return Genlytics::query()->last7Days()->toPageResource();
// Default GA4 purchase funnel (view_item -> add_to_cart -> checkout -> purchase)
$funnel = Genlytics::ecommerceFunnel('30daysAgo');
echo "Overall conversion: {$funnel->overallConversionRate}%
";
// Top products by revenue
$products = Genlytics::topProducts(limit: 10, period: 'last30Days');
// Top product categories
$categories = Genlytics::topCategories(limit: 10, period: 'last30Days');
$batch = Genlytics::getBatchReports([
'top_pages' => [
'period' => 'last7Days',
'dimensions' => ['pagePath'],
'metrics' => ['screenPageViews'],
'limit' => 5
],
'top_countries' => [
'period' => 'last7Days',
'dimensions' => ['country'],
'metrics' => ['activeUsers'],
'limit' => 5
]
]);
use zfhassaan\genlytics\Genlytics;
$analytics = new Genlytics();
use Genlytics;
$result = Genlytics::runReports(...);
use zfhassaan\genlytics\Genlytics;
class AnalyticsController extends Controller
{
public function __construct(
protected Genlytics $analytics
) {}
}
$period = [
'start_date' => '7daysAgo',
'end_date' => 'today'
];
$dimensions = [['name' => 'country']];
$metrics = [['name' => 'activeUsers']];
$result = $analytics->runReports($period, $dimensions, $metrics);
$dimensions = [
['name' => 'country'],
['name' => 'city'],
['name' => 'deviceCategory'],
];
$metrics = [
['name' => 'activeUsers'],
['name' => 'sessions'],
['name' => 'bounceRate'],
];
$result = $analytics->runReports($period, $dimensions, $metrics);
$options = [
'limit' => 100,
'offset' => 0,
'orderBys' => [
[
'metric' => [
'metricName' => 'activeUsers'
],
'desc' => true
]
]
];
$result = $analytics->runReports($period, $dimensions, $metrics, $options);
$result = $analytics->runReports(
$period,
$dimensions,
$metrics,
[],
true // Force refresh from API
);
$dimensions = [['name' => 'country']];
$metrics = [['name' => 'activeUsers']];
$result = $analytics->runRealTime($dimensions, $metrics);
$period = [
'start_date' => '30daysAgo',
'end_date' => 'today'
];
// Single dimension
$result = $analytics->runDimensionReport($period, 'country');
// Multiple dimensions
$result = $analytics->runDimensionReport($period, ['country', 'city']);
// Cache is enabled by default
// Configure in config/analytics.php or .env
GENLYTICS_ENABLE_CACHE=true
GENLYTICS_CACHE_LIFETIME=1440 // 24 hours in minutes
// Enable in config
GENLYTICS_USE_BACKGROUND_JOBS=true
// Requires queue worker
php artisan queue:work
// Enable in config
GENLYTICS_ENABLE_REALTIME_UPDATES=true
GENLYTICS_REALTIME_CACHE_LIFETIME=30 // seconds
use zfhassaan\genlytics\Events\AnalyticsDataFetched;
use Illuminate\Support\Facades\Event;
Event::listen(AnalyticsDataFetched::class, function ($event) {
Log::info('Analytics data fetched', [
'type' => $event->reportType,
'from_cache' => $event->fromCache,
'data_count' => count($event->data),
]);
});
use zfhassaan\genlytics\Contracts\AnalyticsRepositoryInterface;
$repository = app(AnalyticsRepositoryInterface::class);
$response = $repository->runReport(
$dateRange,
$dimensions,
$metrics,
$options
);
use zfhassaan\genlytics\Contracts\CacheManagerInterface;
$cacheManager = app(CacheManagerInterface::class);
// Clear specific cache
$cacheManager->forget('report:abc123');
// Clear all cache
$cacheManager->clear();
class DashboardController extends Controller
{
public function analytics(Genlytics $analytics)
{
$period = [
'start_date' => '30daysAgo',
'end_date' => 'today'
];
$metrics = [['name' => 'activeUsers']];
$users = $analytics->runReports($period, [], $metrics);
return view('dashboard.analytics', [
'users' => $users->getData(true)
]);
}
}
public function liveVisitors(Genlytics $analytics)
{
$metrics = [['name' => 'activeUsers']];
$result = $analytics->runRealTime([], $metrics);
return response()->json([
'visitors' => $result->getData(true)['data'][0]['metrics']['activeUsers'] ?? 0
]);
}
public function topCountries(Genlytics $analytics)
{
$period = ['start_date' => '30daysAgo', 'end_date' => 'today'];
$dimensions = [['name' => 'country']];
$metrics = [['name' => 'activeUsers']];
$options = [
'orderBys' => [
[
'metric' => ['metricName' => 'activeUsers'],
'desc' => true
]
],
'limit' => 10
];
return $analytics->runReports($period, $dimensions, $metrics, $options);
}
try {
$result = $analytics->runReports($period, $dimensions, $metrics);
} catch (\Exception $e) {
Log::error('Analytics error', [
'error' => $e->getMessage(),
]);
return response()->json([
'error' => 'Failed to fetch analytics data'
], 500);
}
bash
php artisan vendor:publish --tag=genlytics-config
bash
php artisan vendor:publish --provider="zfhassaan\genlytics\provider\AnalyticsServiceProvider"
bash
php artisan vendor:publish --tag=genlytics-tests
bash
php artisan genlytics:refresh-cache --clear
bash
php artisan genlytics:refresh-cache --type=report
php artisan genlytics:refresh-cache --type=realtime