CodeIgniter中的静态变量 [英] Static variables in CodeIgniter

查看:178
本文介绍了CodeIgniter中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Model返回的控制器中保存一个结果。结果应该以一种方式保存,当我调用第二个时间控制器而不调用模型时,我可以使用这个数据。我不想将数据放在会话或内存缓存中。

I need to save a result in controller returned by the Model. The results should be save in a way that I can use this data when second time controller is called without calling the model. I don’t want to put the data in session or memcache. What should be the most efficient way to do it?

推荐答案

大多数开始使用PHP的人都不会调用这些静态变量。你从Java迁移了吗?如果你切换到无状态的HTTP - memcached是为此设计的(虽然我不确定APC或其他操作码缓存),这是一个范式转换。基于Cookie的会话是为此设计的。

Most people who started with PHP wouldn't call those "Static Variables." Did you migrate from Java by chance? It's a bit of a paradigm shift if you're switching to the statelessness of HTTP--memcached was designed for this (though I'm not sure APC or other opcode caches were). Cookie-based sessions were kind of designed for this.

如果您想避免对同一请求重复查询,请依赖CI查询缓存(和你的数据库服务器的查询缓存),或使用什么PHP调用静态变量:

If you're trying to avoid repeat queries on the same request, rely on CI's query cache (and your database server's query cache, for that matter), or use what PHP calls "static variables":

class Some_model extends CI_Model {

    protected static $some_result;

    public function getResult()
    {
        if (empty(self::$some_result))
        {
             self::$some_result = $this->db->get('table')->result();
        }

        return self::$some_result;
    }
}

如果查询可能返回空,但你得到的点。它也有点不必要的模型,因为我不认为你可以创建多个实例通过CI_Loader无论如何...

You might have to adjust if the query could possibly return empty, but you get the point. It's also somewhat unnecessary with models, as I don't think you can create more than one instance through the CI_Loader anyway...

这篇关于CodeIgniter中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆