PHP Best way to cache MySQL results?

后端 未结 4 1899
小鲜肉
小鲜肉 2020-12-13 02:09

I am currently building a PHP framework (original, i know) and im working on some optimisation features for it. One dilema I have come accross is what is the best way to ca

4条回答
  •  佛祖请我去吃肉
    2020-12-13 02:46

    Memcached.

    I always try to create my own solution at least once, to grasp better what's going on under the hood in most situations. When I created my own caching solution, I essentially did what you're talking about.

    // serialize an array of all results
    $serialzedData = serialize($resultData);
    
    // set TTL (60 seconds) and create cache filename with timestamp
    $ttl = 60;
    $cacheFilename = $ttl . '_' . time() . '_' . md5($sqlQuery)
    
    // dump
    file_put_contents($cacheFilename, $serializedData);
    

    Prior to a query firing, it would search the cache directory for files with a matching query hash. If it does, it tests timestamp + ttl <= current_time, and if true, returns the unserialized file contents. Otherwise, overwrite it.

提交回复
热议问题