在php中缓存或预加载一些变量

时间:2016-08-04 18:51:58

标签: php mysql

我正在开发基于PHP / MySQL的产品搜索应用程序。在该应用程序中,我们有一些全局变量,这些变量正在从数据库中填充。由于这些变量对于所有搜索请求都是通用的,因此每次搜索请求到达服务器时都不需要填充。

我已经看到了使用memcache和APC的一些建议,但问题是我们无权在服务器中安装这些。有没有方便的方法来保持这些变量只初始化一次并用于所有服务器请求?

一些变量的例子:

$result = $this->db->query("SELECT brand_name FROM brands");
    if ($result->num_rows > 0) {
        foreach ($result->rows as $row) {
            if ($row['brand_name'] != '') {
                $GLOBALS["filter"]['brand_name'][] = $row['brand_name'];
            }
        }
    }

它包含在搜索查询中用于比较的品牌名称。同样,我们还有许多其他预定义的全局变量。

1 个答案:

答案 0 :(得分:1)

如果您有opcache可用,那么您可以执行以下操作:

免责声明:我没有对此进行测试,也没有opcache功能或行为方面的经验。

预定任务(每月?手动?自动?idk,你明白了)

$result = $this->db->query("SELECT brand_name FROM brands");

if ($result->num_rows > 0) {

    $temp_file = '/path/to/cached/file/brands_cache.'.microtime(true).'.php';

    $final_file = '/path/to/cached/file/brands_cache.php';

    file_put_contents($temp_file, '<?php $GLOBALS["filter"]["brand_name"] = [];');

    foreach ($result->rows as $row) {
        if ($row['brand_name'] != '') {
            file_put_contents($temp_file, '$GLOBALS["filter"]["brand_name"][] = \''.str_replace("'", "\\'", $row['brand_name']).'\';', FILE_APPEND);
        }
    }

    rename($temp_file, $final_file);

    if(opcache_compile_file($final_file))
    {
        echo $final_file.' has been cached';
    }
    else
    {
        echo $final_file.' could not be cached';
    }
}

您的搜索引擎

require_once('/path/to/cached/file/brands_cache.php');

// Feel free to use $GLOBALS["filter"]['brand_name']