PHP code example of krowek / view-counter-bundle

1. Go to this page and download the library: Download krowek/view-counter-bundle 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/ */

    

krowek / view-counter-bundle example snippets


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

   use Tchoulom\ViewCounterBundle\Model\ViewCountable;
   
    ...
    class Article implements ViewCountable
    {
      ...
    }

   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);
       }
      ...
    }


    use Tchoulom\ViewCounterBundle\Entity\ViewCounter as BaseViewCounter;
    
    /**
     * ViewCounter.
     *
     * @ORM\Table(name="view_counter")
     * @ORM\Entity()
     */
    class ViewCounter extends BaseViewCounter
    {
        ...
    }



    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;
        }
        
        ...
    }


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();
        ...
    }
 }
...

...

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);
    ...
}



namespace App\Service;

use GeoIp2\Database\Reader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Tchoulom\ViewCounterBundle\Adapter\Geolocator\GeolocatorInterface;

/**
 * Class Geolocator
 *
 * This service must implements the "GeolocationInterface".
 */
class Geolocator implements GeolocatorInterface
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var Reader
     */
    protected $reader;

    /**
     * Geolocator constructor.
     *
     * @param RequestStack $requestStack
     * @param Reader $reader
     */
    public function __construct(RequestStack $requestStack, Reader $reader)
    {
        $this->request = $requestStack->getCurrentRequest();
        $this->reader = $reader;
    }

    /**
     * Gets the record.
     * 
     * @return \GeoIp2\Model\City|mixed
     * @throws \GeoIp2\Exception\AddressNotFoundException
     * @throws \MaxMind\Db\Reader\InvalidDatabaseException
     */
    public function getRecord()
    {
        $clientIp = $this->request->getClientIp();

        return $this->reader->city($clientIp);
    }

    /**
     * Gets the continent.
     *
     * @return string
     * @throws \GeoIp2\Exception\AddressNotFoundException
     * @throws \MaxMind\Db\Reader\InvalidDatabaseException
     */
    public function getContinent(): string
    {
        return $this->getRecord()->continent->name;
    }

    /**
     * Gets the country.
     * 
     * @return string
     * @throws \GeoIp2\Exception\AddressNotFoundException
     * @throws \MaxMind\Db\Reader\InvalidDatabaseException
     */
    public function getCountry(): string
    {
        return $this->getRecord()->country->name;
    }

    /**
     * Gets the region.
     * 
     * @return string
     * @throws \GeoIp2\Exception\AddressNotFoundException
     * @throws \MaxMind\Db\Reader\InvalidDatabaseException
     */
    public function getRegion(): string
    {
        return $this->getRecord()->subdivisions[0]->names['en'];
    }

    /**
     * Gets the city.
     * 
     * @return string
     * @throws \GeoIp2\Exception\AddressNotFoundException
     * @throws \MaxMind\Db\Reader\InvalidDatabaseException
     */
    public function getCity(): string
    {
        return $this->getRecord()->city->name;
    }
}

use Tchoulom\ViewCounterBundle\Finder\StatsFinder:

/**
 * @var StatsFinder
 */
protected $statsFinder;

/**
 * @param StatsFinder $statsFinder
 */
public function __construct(StatsFinder $statsFinder)
{
    $this->statsFinder = $statsFinder;
}

   // The "statsFinder" service
   $statsFinder = $this->get('tchoulom.viewcounter.stats_finder');
   
   // Get all statistical data
   $contents = $statsFinder->loadContents();
   
   // Finds statistics by page
   // Returns an instance of Tchoulom\ViewCounterBundle\Statistics\Page
   $page = $statsFinder->findByPage($article);
    
   // Finds statistics by year (year number: 2019)
   // Returns an instance of Tchoulom\ViewCounterBundle\Statistics\Year
   $year = $statsFinder->findByYear($article, 2019);
     
   // Finds statistics by month (month number: 1)
   // Returns an instance of Tchoulom\ViewCounterBundle\Statistics\Month
   $month = $statsFinder->findByMonth($article, 2019, 1);
   
   // Finds statistics by week (week number: 3)
   // Returns an instance of Tchoulom\ViewCounterBundle\Statistics\Week
   $week = $statsFinder->findByWeek($article, 2019, 1, 3);
   
   // Finds statistics by day (name of the day: 'thursday')
   // Returns an instance of Tchoulom\ViewCounterBundle\Statistics\Day
   $day = $statsFinder->findByDay($article, 2019, 1, 3, 'thursday');
   
   // Finds statistics by hour (time name: 'h17' => between 17:00 and 17:59)
   // Returns an instance of Tchoulom\ViewCounterBundle\Statistics\Hour
   $hour = $statsFinder->findByHour($article, 2019, 1, 3, 'thursday', 'h17');
   
   // Finds statistics by minute (the name of the minute: 'm49' => in the 49th minute)
   // Returns an instance of Tchoulom\ViewCounterBundle\Statistics\Minute
   $minute = $statsFinder->findByMinute($article, 2019, 1, 3, 'thursday', 'h17', 'm49');
   
   // Finds statistics by second (the name of the second: 's19' => in the 19th second)
   // Returns an instance of Tchoulom\ViewCounterBundle\Statistics\Second
   $second = $statsFinder->findBySecond($article, 2019, 1, 3, 'thursday', 'h17', 'm49', 's19');
   

   // Get the yearly statistics
   $yearlyStats = $statsFinder->getYearlyStats($article); 

   [
      [2019,98537215], [2018,95548144], [2017,47882376]
   ]

   // Get the monthly statistics in 2019
   $monthlyStats = $statsFinder->getMonthlyStats($article, 2019);

   [
      [8,951224], [7,921548], [6,845479]
   ]

   // Get the weekly statistics of the month of August (month number 8) in 2019
   $weeklyStats = $statsFinder->getWeeklylyStats($article, 2019, 8);

   [
      [34,494214], [33,117649], [32,183254]
   ]

   // Get the daily statistics of the week number 33 in august 2019
   $dailyStats = $statsFinder->getDailyStats($article, 2019, 8, 33);

   [
      ['Monday',16810],['Tuesday',16804],['Wednesday',16807],['Thursday',16807],['Friday',16807],['Saturday',16807],['Sunday',16807]
   ]

   // Get the hourly statistics for Thursday of the week number 33 in august 2019
   $hourlyStats = $statsFinder->getHourlyStats($article, 2019, 8, 33, 'Thursday');

   [
      ['00',650],['01',750],['02',500],['03',900],['04',700],['05',700],['06',700],['07',700],['08',700],['09',700],['10',700],['11',720],['12',680],['13',700],['14',200],['15',1200],['16',700],['17',700],['18',700],['19',700],['20',100],['21',1300],['22',700],['23',700]
   ]

   // Get the statistics per minute on Saturday of the week number 33 in august 2019 at 15h ('h15')
   $statsPerMinute = $this->get('tchoulom.viewcounter.stats_finder')->getStatsPerMinute($article, 2019, 8, 33, 'Saturday', 'h15');

   [
      ['00',650],['01',740],['02',520],['03',752],['04',700],['05',700],['06',400],['07',400],['08',800],['09',700],['10',700],['11',720],['12',680],['13',700],['14',200],['15',100],['16',105],['17',700],['18',700],['19',700],['20',100],['21',130],['22',700],['23',700],['24',110],['25',210],['26',110],['27',10],['28',110],['29',10],['30',141],['31',148],['32',181],['33',141],['34',141],['35',171],['36',141],['37',181],['38',141],['39',141],['40',191],['41',193],['42',194],['43',194],['44',191],['45',191],['46',148],['47',191],['48',191],['49',191],['50',191],['51',151],['52',131],['53',191],['54',171],['55',191],['56',111],['57',191],['58',254],['59',91]
   ]

   // Get the statistics per second on Saturday of the week number 33 in august 2019 at 15H49
   $statsPerSecond = $this->get('tchoulom.viewcounter.stats_finder')->getStatsPerSecond($article, 2019, 8, 33, 'Saturday', 'h15', 'm49');

   [
      ['00',60],['01',40],['02',21],['03',72],['04',70],['05',70],['06',50],['07',20],['08',80],['09',70],['10',70],['11',72],['12',68],['13',70],['14',20],['15',10],['16',15],['17',70],['18',70],['19',70],['20',10],['21',13],['22',70],['23',7],['24',11],['25',21],['26',11],['27',10],['28',110],['29',10],['30',14],['31',14],['32',18],['33',14],['34',14],['35',17],['36',14],['37',18],['38',14],['39',14],['40',19],['41',19],['42',19],['43',19],['44',19],['45',19],['46',18],['47',19],['48',19],['49',19],['50',19],['51',15],['52',13],['53',19],['54',17],['55',19],['56',11],['57',19],['58',25],['59',71]
   ]

$countryStats = $this->statFinder->getCountryStats($article);

   [
      ["France", 6],["United States", 45],["Ireland", 8],["United Kingdom", 8]
   ]

$regionStats = $this->statFinder->getRegionStats($article);

   [
      ["Île-de-France", 3],["Normandy", 3],["District of Columbia", 44],["New York", 1],["Leinster", 8],["England", 2]
   ]

$cityStats = $this->statFinder->getCityStats($article);

   [
      ["Paris", 3],["Rouen", 3],["Washington", 44],["Buffalo", 1],["Dublin", 8],["London", 2]
   ]

$statsByCountry = $this->statFinder->getStatsByCountry($article, 'United States');

  45

$statsByRegion = $this->statFinder->getStatsByRegion($article, 'United States', 'District of Columbia');

  44

$statsByCity = $this->statFinder->getStatsByCity($article, 'United States', 'District of Columbia', 'Washington');

  44

   $statsComputer = $this->get('tchoulom.viewcounter.stats_computer');

   // Get the min value of the yearly statistics
   $minValue = $statsComputer->computeMinValue($yearlyStats);

    [2017,47882376]

   // Get the max value of the monthly statistics
   $maxValue = $statsComputer->computeMaxValue($monthlyStats);

    [8,951224]

   // Get the average of the weekly statistics
   $average = $statsComputer->computeAverage($weeklyStats);

    265039

   // Get the range of the daily statistics
   $range = $statsComputer->computeRange($dailyStats);

    6

   // Get the mode of the hourly statistics
   $mode = $statsComputer->computeMode($hourlyStats);

    700

   // Get the median of the statistics per minute
   $median = $statsComputer->computeMedian($statsPerMinute);

    75.5

   // Get the count of the statistics per second
   $count = $statsComputer->count($statsPerSecond);

    60
 bash
  $ php composer.phar update tchoulom/view-counter-bundle
  
bash
   php bin/console tchoulom:viewcounter:cleanup
bash
   php bin/console tchoulom:viewcounter:cleanup --min=1h
bash
   php bin/console tchoulom:viewcounter:cleanup --max=1d
bash
   php bin/console tchoulom:viewcounter:cleanup --min=3y
bash
   php bin/console tchoulom:viewcounter:cleanup --max=5M