Laravel 5 - Device Detector Cache Proxy

Łukasz Piotrowski Comments 0

    DeviceDetector is a tool which based on UserAgent detects and returns us very useful information like browser, device, system etc.

    It has very interesting option to detect if user which browse our page is bot or not.

    Using this tool you can use Cache. By default it supports doctrine/cache. We can by own implement cache. To do this we need to implement interface DeviceDetector\Cache\Cache.

    I decided to write my own very simple Proxy which You can use with current using Cache system implemented in Laravel 5


    Description

    This Proxy is based on current use Cache Driver. We can select it in .env on CACHE_DRIVER variable.

    By default class should be in app/Proxy/DeviceDetectorCacheProxy.php

    Class

    <?php
    
    namespace App\Proxy;
    
    use DeviceDetector\Cache\Cache;
    
    /**
     * Class used as Proxy between Device Detector and Laravel system cache.
     *
     * Class DeviceDetectorCacheProxy
     * @package App\Proxy
     */
    class DeviceDetectorCacheProxy implements Cache
    {
        /** @var \Illuminate\Contracts\Cache\Repository|\Illuminate\Contracts\Cache\Store $driver */
        protected $driver;
    
        /**
         * DeviceDetectorCacheProxy constructor.
         *
         * @param null $driver Driver used in Laravel
         */
        public function __construct($driver = null)
        {
            $this->driver = app('cache')->driver($driver);
        }
    
        /**
         * Fetch item from Cache
         *
         * @param $id
         * @return mixed
         */
        public function fetch($id)
        {
            return $this->driver->get($id);
        }
    
        /**
         * Check is cache has $id.
         * @param $id
         */
        public function contains($id)
        {
            $this->driver->has($id);
        }
    
        /**
         * Save data to cache.
         *
         * @param $id
         * @param $data
         * @param int $lifeTime
         */
        public function save($id, $data, $lifeTime = 0)
        {
            $this->driver->add($id, $data, $lifeTime);
        }
    
        /**
         * Delete key from Cache
         *
         * @param $id
         */
        public function delete($id)
        {
            $this->driver->forget($id);
        }
    
        /**
         * Remove all data from cache
         */
        public function flushAll()
        {
            $this->driver->flush();
        }
    
        /**
         * Returns current used driver
         *
         * @return \Illuminate\Contracts\Cache\Repository|\Illuminate\Contracts\Cache\Store
         */
        public function getDriver()
        {
            return $this->driver;
        }
    }
    Top