petrhejna/server-side-page-view-counter

Server side visit counter for PHP applications.

dev-master 2019-07-12 21:28 UTC

README

Build Status

Server side visit counter for PHP applications

composer require petrhejna/server-side-page-visit-counter

Usage

Building dependencies

Building dependencies using Airtable (you can use your own storage by implementing PageViewStorage interface):


    $airtable = new TANIOS\Airtable\Airtable([
        'api_key' => '****',
        'base' => 'Your Base',
    ])
    $pageViewStorage = new AirtablePageViewStorage('page_views', $airtable);
    $pageViewFromRequestFactory = new PageViewFromRequestFactory(...); // fill dependencies
    $pageViewCounter = new PageViewCounter(['/ignored/path.js.map'], $ageViewStorage);
    
    $pageViewCounterMiddleware = new PageViewCounterMiddleware($pageViewCounter, ...);

If you are using Nette Dependency Container you can use this example of neon configuration:

services:
    airtable: Guym4c\Airtable\Airtable(%airtable.apiKey%, %airtable.base%)
    - PetrHejna\ServerSidePageViewCounter\PageViewFromRequestFactory
    - PetrHejna\ServerSidePageViewCounter\Storage\Airtable\FilterFormulaFactory
    pageViewStorage: PetrHejna\ServerSidePageViewCounter\Storage\Airtable\AirtablePageViewStorage('page_views', @airtable)
    - PetrHejna\ServerSidePageViewCounter\PageViewCounter(['/ignored/path.js.map'], @pageViewStorage)

Using counter

Example from PSR based application using middleware architecture:

final class PageViewCounterMiddleware implements Middleware
{
    /** @var PageViewCounter  */
    private $pageViewCounter;

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface {
        $next = $this->next;
        $response = $this->pageViewCounter->countVisit($request, $response);
        return $next($request, $response);
    }
}

Counting

Airtable storage is implemented in the way, that for already existing visit does NOT create new records but adds +1 to count field and updates viewedAt time.

Tracking visitors via cookie

This library adds visitorId into cookie. Method countVisit returns ResponseInterface object with Set-Cookie header for visitorId cookie. If no cookie set, the counter will generate new one.

Ignored paths

Sometimes, there are paths that you dont want to track. You can set array of ingored paths via first argument of PageViewCounter constructor.