PHP优化sql调用

时间:2015-04-07 09:16:10

标签: php

我的应用程序中有1个函数被多次调用。每次返回相同的结果。在一个页面上,它被调用5至6次。有没有什么方法可以减少这些调用,比如在某个变量中存储数据,如果它不为空则返回相同的数据。

感谢任何帮助。

这是功能:

public function getResponse($connection)
{
    $query="select * from test order by date DSC";
    $arr = $connection ->query($query); //fetch all the data from query                   
    return $arr;
}

2 个答案:

答案 0 :(得分:2)

如前所述,您已经回答了问题,但如果您是PHP新手,那么您可以使用以下代码:

// define variable
$response = null;

// then everywhere you're currently calling it, you could use:
$response = ($response == null) ? getResponse($conn) : $response;

基本上这会检查变量是否已经保存了函数返回的值(即已经调用过),如果是,则使用该值,否则调用函数并将返回的值存储在变量$ response中。

希望这会有所帮助:)

答案 1 :(得分:2)

听起来你想要这样的东西。

但是,您应该缓存响应,您应该从响应中捕获数据(行)。否则,您将遇到指针问题和其他问题。相反,您要对结果行执行任何数据转换,并以类似的方式存储它们。

private $_response_cache = null;
public function getResponse($connection)
{
    if (is_null($this->_response_cache))
    {
        $query="select * from test order by date DSC";
        $this->_response_cache = $connection ->query($query); //fetch all the data from query                   
    }
    return $this->_response_cache;
}

如果您需要静态,这里......但更多警告。静态代码在构造函数之外是有问题的,应谨慎使用。它与单元测试相结合,可能会产生奇怪的副作用 - 有一所大型学校建议不要使用它,虽然我没有订阅该学校,但我确实认为不正确的使用既简单又危险。

private static $_response_cache = null;
public function getResponse($connection)
{
    if (is_null(self::$_response_cache))
    {
        $query="select * from test order by date DSC";
        self::$_response_cache = $connection ->query($query); //fetch all the data from query                   
    }
    return self::$_response_cache;
}