PHPackages                             krowek/view-counter-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. krowek/view-counter-bundle

ActiveSymfony-bundle

krowek/view-counter-bundle
==========================

The "View Counter" bundle

4.5.3(5y ago)08MITPHPPHP &gt;=7.2.5

Since Oct 15Pushed 5y agoCompare

[ Source](https://github.com/krowek/ViewCounterBundle)[ Packagist](https://packagist.org/packages/krowek/view-counter-bundle)[ RSS](/packages/krowek-view-counter-bundle/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (2)Versions (55)Used By (0)

The View Counter Bundle
=======================

[](#the-view-counter-bundle)

Welcome to the "**TchoulomViewCounterBundle**".

This bundle is used to count the number of views of a web page (the viewership).

This bundle can also be used to draw a graphical representation of statistical data of the web pages.

[![Monthly views in 2018](https://raw.githubusercontent.com/tchoulom/ViewCounterBundle/master/Resources/doc/images/monthly-views-2018.png)](https://raw.githubusercontent.com/tchoulom/ViewCounterBundle/master/Resources/doc/images/monthly-views-2018.png)

**Table of contents**

- [Features include](#features-include)
- [Documentation](#documentation)
- [Installation](#installation)
    - [Step 1: Download TchoulomViewCounterBundle using composer](#step-1-download-tchoulomviewcounterbundle-using-composer)
    - [Step 2: Enable the Bundle](#step-2-enable-the-bundle)
- [Usage](#usage)
    - [Step 1: Interface and Property](#step-1-interface-and-property)
    - [Step 2: ViewCounter](#step-2-viewcounter)
    - [Step 3: Configuration](#step-3-configuration)
        - [The "view\_counter"](#the-view_counter)
        - [The "statistics"](#the-statistics)
    - [Step 4: The Controller](#step-4-the-controller)
        - [Method 1](#method-1)
        - [Method 2](#method-2)
    - [Step 5: The View](#step-5-the-view)
    - [Step 6: The Geolocation](#step-6-the-geolocation)
    - [Step 7: Exploitation of statistical data](#step-7-exploitation-of-statistical-data)
        - [The *StatsFinder* service](#the-statsfinder-service)
            - [Get the *yearly* statistics](#get-the-yearly-statistics)
            - [Get the *monthly* statistics](#get-the-monthly-statistics)
            - [Get the *weekly* statistics](#get-the-weekly-statistics)
            - [Get the *daily* statistics](#get-the-daily-statistics)
            - [Get the *hourly* statistics](#get-the-hourly-statistics)
            - [Get the statistics *per minute*](#get-the-statistics-per-minute)
            - [Get the statistics *per second*](#get-the-statistics-per-second)
            - [Search for geolocation data](#search-for-geolocation-data)
        - [Build a graph with "Google Charts"](#build-a-graph-with-google-charts)
        - [The *StatsComputer* service](#the-statscomputer-service)
            - [Calculates the *min value*](#calculates-the-min-value)
            - [Calculates the *max value*](#calculates-the-max-value)
            - [Calculates the *average*](#calculates-the-average)
            - [Calculates the *range*](#calculates-the-range)
            - [Calculates the *mode*](#calculates-the-mode)
            - [Calculates the *median*](#calculates-the-median)
            - [Count the number of values ​​in the statistical series](#count-the-number-of-values-in-the-statistical-series)
- [Tools](#tools)
    - [Command](#command)
        - [Cleanup viewcounter data](#cleanup-viewcounter-data)
- [Original Credits](#original-credits)
- [License](#license)

Features include
================

[](#features-include)

```
- Viewcounter
- Statistics
- Geolocation

```

Documentation
=============

[](#documentation)

[The ViewCounter documentation](http://tchoulom.com/fr/tutoriel/the-view-counter-bundle-1)

Installation
============

[](#installation)

Step 1: Download TchoulomViewCounterBundle using composer
---------------------------------------------------------

[](#step-1-download-tchoulomviewcounterbundle-using-composer)

You can install it via Composer:

```
$ php composer.phar update tchoulom/view-counter-bundle
```

or

```
 $ composer require tchoulom/view-counter-bundle
```

or

```
 $ composer req tchoulom/view-counter-bundle
```

Check that it is recorded in the **composer.json** file

```
{
    "require": {
        ...
        "tchoulom/view-counter-bundle": "^4.0"
        ...
    }
}
```

Step 2: Enable the Bundle
-------------------------

[](#step-2-enable-the-bundle)

Edit the **appKernel.php** file

```
    ...
    $bundles = array(
	     ...
	     new Tchoulom\ViewCounterBundle\TchoulomViewCounterBundle(),
	     ...
      );
     ...
```

Usage
=====

[](#usage)

Step 1: Interface and Property
------------------------------

[](#step-1-interface-and-property)

Suppose that you have an **Article** Entity.

This Entity must implement the **ViewCountable** interface:

```
   use Tchoulom\ViewCounterBundle\Model\ViewCountable;

    ...
    class Article implements ViewCountable
    {
      ...
    }
```

Add the **$views** property and the target Entity **ViewCounter**.

The **$views** property allows to get the number of views:

```
   use Tchoulom\ViewCounterBundle\Model\ViewCountable;
   use Entity\ViewCounter;
   use Doctrine\Common\Collections\ArrayCollection;

    ...

    class Article implements ViewCountable
    {
      ...

    /**
      * @var integer
      * @ORM\Column(name="id", type="integer")
      * @ORM\Id
      * @ORM\GeneratedValue(strategy="AUTO")
      */
     protected $id;

      /**
       * @ORM\OneToMany(targetEntity="Entity\ViewCounter", mappedBy="article")
       */
      protected $viewCounters;

      /**
      * @ORM\Column(name="views", type="integer", nullable=true)
      */
       protected $views = 0;

       /**
        * Constructor
        */
       public function __construct()
       {
           $this->viewCounters = new ArrayCollection();
       }

        /**
        * Gets id
        *
        * @return integer
        */
        public function getId()
        {
            return $this->id;
        }

       /**
        * Sets $views
        *
        * @param integer $views
        *
        * @return $this
        */
       public function setViews($views)
       {
           $this->views = $views;

           return $this;
       }

       /**
        * Gets $views
        *
        * @return integer
        */
       public function getViews()
       {
           return $this->views;
       }

       /**
        * Get $viewCounters
        *
        * @return Collection
        */
       public function getViewCounters()
       {
           return $this->viewCounters;
       }

       /**
        * Add $viewCounter
        *
        * @param ViewCounter $viewCounter
        *
        * @return $this
        */
       public function addViewCounter(ViewCounter $viewCounter)
       {
           $this->viewCounters[] = $viewCounter;

           return $this;
       }

       /**
        * Remove $viewCounter
        *
        * @param ViewCounter $viewCounter
        */
       public function removeViewCounter(ViewCounter $viewCounter)
       {
           $this->viewCounters->removeElement($viewCounter);
       }
      ...
    }
```

Step 2: ViewCounter
-------------------

[](#step-2-viewcounter)

The **ViewCounter** Entity allows to set the IP address, the **view\_date**, and the **article\_id**.

The **ViewCounter** Entity must extend the **BaseViewCounter**:

```
    use Tchoulom\ViewCounterBundle\Entity\ViewCounter as BaseViewCounter;

    /**
     * ViewCounter.
     *
     * @ORM\Table(name="view_counter")
     * @ORM\Entity()
     */
    class ViewCounter extends BaseViewCounter
    {
        ...
    }
```

Update the doctrine relationship between the **ViewCounter** Entity and your **Article** Entity:

```
    use Tchoulom\ViewCounterBundle\Entity\ViewCounter as BaseViewCounter;

    /**
     * ViewCounter.
     *
     * @ORM\Table(name="view_counter")
     * @ORM\Entity()
     */
    class ViewCounter extends BaseViewCounter
    {
        ...

        /**
         * @ORM\ManyToOne(targetEntity="Article", cascade={"persist"}, inversedBy="viewCounters")
         * @ORM\JoinColumn(nullable=true)
         */
        private $article;

        /**
         * Gets article
         *
         * @return Article
         */
        public function getArticle()
        {
            return $this->article;
        }

        /**
         * Sets Article
         *
         * @param Article $article
         *
         * @return $this
         */
        public function setArticle(Article $article)
        {
            $this->article = $article;

            return $this;
        }

        ...
    }
```

Step 3: Configuration
---------------------

[](#step-3-configuration)

###### For symfony 4 or 5:

[](#for-symfony-4-or-5)

- Create the file **config/packages/tchoulom\_viewcounter.yaml**
- Add the following viewcounter configuration in the **tchoulom\_viewcounter.yaml** file.

###### For version of symfony less than 4:

[](#for-version-of-symfony-less-than-4)

- Add the following viewcounter configuration in the **app/config.yml** file.

##### viewcounter configuration:

[](#viewcounter-configuration)

```
    tchoulom_view_counter:
        view_counter:
            view_strategy: daily_view
        statistics:
            use_stats: false
            stats_file_name: stats
            stats_file_extension:
        geolocation:
            geolocator_id: App\Service\Geolocator
```

### The "view\_counter"

[](#the-view_counter)

The different values of ***view\_strategy*** are : daily\_view, unique\_view, increment\_each\_view, hourly\_view, weekly\_view, monthly\_view, yearly\_view, view\_per\_minute, view\_per\_second.

- The **daily\_view** allows to increment **daily**, for a given **IP** address, the number of views of an **Article** (the viewership). In fact it increments the **$views** property.
- The **unique\_view** allows to set to **1**, for a given **IP** address, the number of view of an article
- The **increment\_each\_view** allows to increment the number of views of an **Article** every time the user will refresh the page
- The **hourly\_view** allows to increment **hourly**, for a given **IP** address, the number of views of an **Article** (the viewership).
- The **weekly\_view** allows to increment **weekly**, for a given **IP** address, the number of views of an **Article** (the viewership).
- The **monthly\_view** allows to increment **monthly**, for a given **IP** address, the number of views of an **Article** (the viewership).
- The **yearly\_view** allows to increment **yearly**, for a given **IP** address, the number of views of an **Article** (the viewership).
- The **view\_per\_minute** allows to increment **every minute**, for a given **IP** address, the number of views of an **Article** (the viewership).
- The **view\_per\_second** allows to increment **every second**, for a given **IP** address, the number of views of an **Article** (the viewership).

### The "statistics"

[](#the-statistics)

The **use\_stats** allows to indicate if you want to use statistics.

If **use\_stats** is set to ***true***, statistics functionality will be used (confers the ***Step 6***).

The **stats\_file\_name** allows to define the name of the statistics file.

The default name of **stats\_file\_name** is **stats**

The **stats\_file\_extension** allows to define the extension of the statistics file.

**Example :**

If **stats\_file\_extension: txt**, then the default name of the statistics file will be ***stats.txt***

If **stats\_file\_extension:**, then the default name of the statistics file will be ***stats***

The full path of the statistics file is ***var/viewcounter*** of your project.

### The "geolocation"

[](#the-geolocation)

The Geolocation defines a service which will allow you to geolocate page visits.

The **geolocator\_id** corresponds to the **identifier** or the **name of the class** of your geolocation service, depending on the version of symfony used:

```
    tchoulom_view_counter:
        ...
        geolocation:
            geolocator_id: app.service.geolocator
```

or

```
    tchoulom_view_counter:
        ...
        geolocation:
            geolocator_id: App\Service\Geolocator
```

if your service is declared as such:

```
    app.service.geolocator:
        class: App\Service\Geolocator
```

You must then set up your "Geolocator" service as we will see in this documentation [Step 6: The Geolocation](#step-6-the-geolocation).

###### You must comment on the geolocation configuration if you do not want to use it in your project:

[](#you-must-comment-on-the-geolocation-configuration-if-you-do-not-want-to-use-it-in-your-project)

```
    tchoulom_view_counter:
        ...
        # geolocation:
        #    geolocator_id: app.service.geolocator
```

Step 4: The Controller
----------------------

[](#step-4-the-controller)

2 methods are available:

### Method 1

[](#method-1)

```
use App\Entity\ViewCounter;
use Tchoulom\ViewCounterBundle\Counter\ViewCounter as Counter;
...

// For Symfony 4 or 5, inject the ViewCounter service

/**
 * @var Counter
 */
protected $viewcounter;

/**
 * @param Counter $viewCounter
 */
public function __construct(Counter $viewCounter)
{
    $this->viewcounter = $viewCounter;
}

/**
 * Reads an existing article
 *
 * @Route("/read/{id}", name="read_article")
 * @ParamConverter("article", options={"mapping": {"id": "id"}})
 * @Method({"GET", "POST"})
 */
 public function readAction(Request $request, Article $article)
 {
    // Viewcounter
    $viewcounter = $this->get('tchoulom.viewcounter')->getViewCounter($article);
    // For Symfony 4 or 5
    $viewcounter = $this->viewcounter->getViewCounter($article);

    $em = $this->getDoctrine()->getEntityManager();

    if ($this->viewcounter->isNewView($viewcounter)) {
        $views = $this->viewcounter->getViews($article);
        $viewcounter->setIp($request->getClientIp());
        $viewcounter->setArticle($article);
        $viewcounter->setViewDate(new \DateTime('now'));

        $article->setViews($views);

        $em->persist($viewcounter);
        $em->persist($article);
        $em->flush();
        ...
    }
 }
...
```

### Method 2

[](#method-2)

You only need to save your **Article** Entity via the **'tchoulom.viewcounter'** service:

```
...

use Tchoulom\ViewCounterBundle\Counter\ViewCounter as Counter;

// For Symfony 4 or 5, inject the ViewCounter service

/**
 * @var Counter
 */
protected $viewcounter;

/**
 * @param Counter $viewCounter
 */
public function __construct(Counter $viewCounter)
{
    $this->viewcounter = $viewCounter;
}

/**
 * Reads an existing article
 *
 * @Route("/read/{id}", name="read_article")
 * @ParamConverter("article", options={"mapping": {"id": "id"}})
 * @Method({"GET", "POST"})
 */
public function readAction(Request $request, Article $article)
{
    // Saves the view
    $page = $this->get('tchoulom.viewcounter')->saveView($article);
    // For Symfony 4 or 5
    $page = $this->viewcounter->saveView($article);
    ...
}
```

The second method returns the current page ($article).

You can choose the method that is most appropriate for your situation.

Step 5: The View
----------------

[](#step-5-the-view)

Finally you can display the number of views:

```
...
The number of views of this article : {{ article.views }}
...
```

Step 6: The Geolocation
-----------------------

[](#step-6-the-geolocation)

Some bundles can be used to have a geolocation system in your project. These bundles usually use the ip address in order to geolocate the visitor of the web page.

For the purposes of this documentation, we will use this bundle, for example:

**gpslab/geoip2** :

You can read the documentation for installing and using this bundle if you want to use it.

Otherwise, you can use another geolocation bundle according to your preferences.

***Create the "Geolocator" service that will allow you to manage geolocation data***

```
