避免数据库频繁查询,对变动频率不高,经常用的数据,可以缓存起来。免得总是查询数据库。这里总结一个手动写cache的方式。

先了解两个api。
1,var_export方法。var_export,输出或返回一个变量的字符串表示。可以将变量内容打印到一个PHP文件里,使用include的方式来重新获取变量内容。这个就是手段。
2,file_put_contents方法。file_put_contents可以写入数据到文件中。比如,php文件,txt文件,图片文件。
通过上边两步,就可以将想要的数据写入到php文件中。

整个的流程是这样的。
1,先通过is_file方法判断缓存文件是否存在。如果存在,直接return include文件。否则,则查询数据库,得到数据,处理数据,写入php文件中。返回数据。
注意,判断一个文件是否存在还可用file_exists。其效率没is_file好。另外,is_file有缓存。各种细节需要注意。if_file不能判断路径,文件夹,file_exists可以。is_dir可以用来判断路径的。

参考:http://www.opstool.com/article/262

这里给个实例code。实例code是ci框架的查询写法:

    public function login($account, $password)
    {
        $path = FCPATH. 'static/cache/user_'. $account. '.php';

        if(FALSE === is_file($path))
        {    
            $db = $this->load->database('vinixiu', TRUE);
            $query = $db->select(array('uid', 'nickname', 'sex', 'email', 'signature'))
                        ->from('accounts')
                        ->where('account', $account)
                        ->where('password', $password)
                        ->get();
            
            $db->close();

            if(FALSE === $query)
            {
                $this->error = $db->_error_number();
                $this->msg = $db->_error_message();
                return FALSE;
            }

            if(0 === $query->num_rows())
            {
                $this->error = 10087;
                $this->msg = 'account or password error!';
                return FALSE;
            }

            $user = array();
            $row = $query->row();

            if(isset($row))
            {
                $user['uid'] = $row->uid;
                $user['nickname'] = $row->nickname;
                $user['sex'] = $row->sex;
                $user['email'] = $row->email;
                $user['signature'] = $row->signature;
            }
            unset($row);
            @file_put_contents($path, '<?php'. "\n return ". var_export($user, TRUE). ";\n", LOCK_EX);
            return $user;
        }
        return include($path);
    }