讓Laravel5支持memcache的方法


Laravel5框架在Cache和Session中不支持Memcache,看清了是Memcache而不是Memcached哦,MemCached是支持的但是這個擴展真的是裝的蛋疼,只有修改部分源碼讓其來支持memcache了。具體修改部分如下:

找到sessioni管理器 Laravel\vendor/laravel/framework/src/Illuminate/Session/SessionManager.php,並增加如下代碼:

/**
     * Create an instance of the Memcached session driver.
     *
     * @return IlluminateSessionStore
     */
    protected function createMemcacheDriver()
    {
        return $this->createCacheBased('memcache');
    }

接下來修改cache部分,找到Laravel/vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php
在該文件中增加以下代碼:

/**
     * Create an instance of the Memcache cache driver.
     *
     * @return IlluminateCacheMemcachedStore
     */
    protected function createMemcacheDriver(array $config)
    {
        $prefix = $this->getPrefix($config);

        $memcache = $this->app['memcache.connector']->connect($config['servers']);

        return $this->repository(new MemcacheStore($memcache, $prefix));
    }

接下來找到文件: Laravel/vendor/laravel/framework/src/Illuminate/Cache/CacheServiceProvider.php 將memcache注冊進去
修改如下:

/**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('cache', function ($app) {
            return new CacheManager($app);
        });

        $this->app->singleton('cache.store', function ($app) {
            return $app['cache']->driver();
        });

        $this->app->singleton('memcached.connector', function () {
            return new MemcachedConnector;
        });

        $this->app->singleton('memcache.connector',function() {
       // 這里返回了MemcacheConnector,記得在Cache目錄下創建這個class
return new MemcacheConnector; }); $this->registerCommands(); }

/**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [
            'cache', 'cache.store', 'memcached.connector', 'command.cache.clear','memcache.connector'
        ];
    }

我們看到這個閉包函數中返回了MemcacheContector的對象,現在來創建此類。文件位置:Laravel/vendor/laravel/framework/src/Illuminate/Cache/MemcacheConnector.php

<?php
namespace Illuminate\Cache;

use Memcache;
use RuntimeException;

class MemcacheConnector {

    /**
     * Create a new Memcached connection.
     *
     * @param array  $servers
     * @return Memcache
     */
    public function connect(array $servers)
    {
        $memcache = $this->getMemcache();

        // For each server in the array, we'll just extract the configuration and add
        // the server to the Memcache connection. Once we have added all of these
        // servers we'll verify the connection is successful and return it back.
        foreach ($servers as $server)
        {
            $memcache->addServer($server['host'], $server['port'], $server['weight']);
        }

        if ($memcache->getVersion() === false)
        {
            throw new RuntimeException("Could not establish Memcache connection.");
        }

        return $memcache;
    }

    /**
     * Get a new Memcache instance.
     *
     * @return Memcached
     */
    protected function getMemcache()
    {
        return new Memcache;
    }
}

按照第二步的流程這個文件會執行connect的方法,執行完成之后返回一個Memcache的對象, 這時候第二步那里根據這邊來創建了一個MemcacheStore的存儲器。

文件地址:Laravel/vendor/laravel/framework/src/Illuminate/Cache/MemcacheStore.php

<?php

namespace Illuminate\Cache;

use Memcache;
use Illuminate\Contracts\Cache\Store;

class MemcacheStore extends TaggableStore implements Store
{
    /**
     * The Memcached instance.
     *
     * @var \Memcached
     */
    protected $memcached;

    /**
     * A string that should be prepended to keys.
     *
     * @var string
     */
    protected $prefix;

    public function __construct(Memcache $memcache, $prefix = '')
    {
        $this->memcache = $memcache;
        $this->prefix = strlen($prefix) > 0 ? $prefix.':' : '';
    }

    /**
     * Retrieve an item from the cache by key.
     *
     * @param  string|array  $key
     * @return mixed
     */
    public function get($key)
    {
        return $this->memcache->get($this->prefix.$key);
    }


    /**
     * Retrieve multiple items from the cache by key.
     *
     * Items not found in the cache will have a null value.
     *
     * @param  array  $keys
     * @return array
     */
    public function many(array $keys)
    {
        $prefixedKeys = array_map(function ($key) {
            return $this->prefix.$key;
        }, $keys);

        $values = $this->memcache->getMulti($prefixedKeys, null, Memcache::GET_PRESERVE_ORDER);

        if ($this->memcache->getResultCode() != 0) {
            return array_fill_keys($keys, null);
        }

        return array_combine($keys, $values);
    }

    /**
     * Store an item in the cache for a given number of minutes.
     *
     * @param  string  $key
     * @param  mixed   $value
     * @param  int     $minutes
     * @return void
     */
    public function put($key, $value, $minutes)
    {
        $compress = is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED;
        $this->memcache->set($this->prefix.$key, $value, $compress, $minutes * 60);
    }

    /**
     * Store multiple items in the cache for a given number of minutes.
     *
     * @param  array  $values
     * @param  int  $minutes
     * @return void
     */
    public function putMany(array $values, $minutes)
    {
        $prefixedValues = [];

        foreach ($values as $key => $value) {
            $prefixedValues[$this->prefix.$key] = $value;
        }

        $this->memcache->setMulti($prefixedValues, $minutes * 60);
    }
     /**
     * Store an item in the cache if the key doesn't exist.
     *
     * @param  string  $key
     * @param  mixed   $value
     * @param  int     $minutes
     * @return bool
     */
    public function add($key, $value, $minutes)
    {
        return $this->memcache->add($this->prefix.$key, $value, $minutes * 60);
    }

    /**
     * Increment the value of an item in the cache.
     *
     * @param  string  $key
     * @param  mixed   $value
     * @return int|bool
     */
    public function increment($key, $value = 1)
    {
        return $this->memcache->increment($this->prefix.$key, $value);
    }

    /**
     * Decrement the value of an item in the cache.
     *
     * @param  string  $key
     * @param  mixed   $value
     * @return int|bool
     */
    public function decrement($key, $value = 1)
    {
        return $this->memcache->decrement($this->prefix.$key, $value);
    }

    /**
     * Store an item in the cache indefinitely.
     *
     * @param  string  $key
     * @param  mixed   $value
     * @return void
     */
    public function forever($key, $value)
    {
        $this->put($key, $value, 0);
    }

    /**
     * Remove an item from the cache.
     *
     * @param  string  $key
     * @return bool
     */
    public function forget($key)
    {
        return $this->memcache->delete($this->prefix.$key);
    }

    /**
     * Remove all items from the cache.
     *
     * @return void
     */
    public function flush()
    {
        $this->memcache->flush();
    }

    /**
     * Get the underlying Memcached connection.
     *
     * @return \Memcached
     */
    public function getMemcached()
    {
        return $this->memcache;
    }

    /**
     * Get the cache key prefix.
     *
     * @return string
     */
    public function getPrefix()
    {
        return $this->prefix;
    }

    /**
     * Set the cache key prefix.
     *
     * @param  string  $prefix
     * @return void
     */
    public function setPrefix($prefix)
    {
        $this->prefix = ! empty($prefix) ? $prefix.':' : '';
    }
}

上述步驟操作完成后,接下來修改一下config.php中的驅動部分,增加如下代碼段:

// 修改為memcached
'default' => env('CACHE_DRIVER', 'memcache'),

// stores 部分增加memcache配置
'memcache' => [
    'driver'  => 'memcache',
    'servers' => [
        [
            'host' => env('MEMCACHED_HOST', '127.0.0.1'),
            'port' => env('MEMCACHED_PORT', 11211),
            'weight' => 100,
        ],
    ],
],

 

至此完工,盡情享用吧。

后話,不知是不是c/c++搞多了的原因,剛開始用php做項目時其實我很不喜歡這些框架,原始慣了什么都喜歡自己來寫,后來發現不對呀現在網絡發展得太快了,什么都自己來造的話明顯是力不從心了,后來接觸了第一個框架CI,用它做了個項目還不錯,再后來看到大家都在說這個Laravel,自己跟着也看看怎么樣,說實話你不用它來做項目的話還真不知道它的便捷性,就這樣用它做了個網站感覺挺不錯呢,就這樣邊學習邊用上了。大家沒試過的話其實可以試一試,畢竟什么都嘗試一下才知道什么適合自己。

最后放個自己的小廣告吧,這個就是我Laravel的第一個網站雲南土特產,見笑了。想爽點純正雲南土特產的朋友也可以試一試。 網址:http://www.orangemall.cc (橘子坊雲南土特產), my god!我去,心都碎了,怎么我的內容里不能搞鏈接,是等級不夠嗎???? 還是不愛寫文章的原因,望指點!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM