0

What is the best way in PHP to do variable caching? For example, let's assume I have a table, with 4 rows.

         name |  job
--------------------------
 Justin Smith | Plumber
 Jack Sparrow | Carpenter
 Justin Smith | Plumber
  Katie White | Doctor

Which is built like:

foreach($people as $person) {
   echo $person->name;
   echo get_job($person->name);
}

And the function call get_job() looks like:

function get_job($name) {
  //This is pseudo code below
  $row = MySQL->Query("SELECT job FROM people WHERE name = $name");
  return $row->job;
}

As you can see, once we get the job of Justin Smith, further down we shouldn't and don't need to do a full MySQL query again, since we know it is Plumber.

I was thinking of doing a global variable which is a key=>value array like:

 global $jobs = array("Justin Smith" => "Plumber",
                      "Jack Sparrow" => "Carpenter",
                      "Katie White" => "Doctor");

Then in the get_job() function I simply just check if the name exists in the array before querying. If not, insert the name and job into the array and return the job.

Basically, is there a better way to do this that is more elegant?

4

2 回答 2

1

有很多可能的解决方案。您可以将 SQL 结果存储在一个数组中,您可以在页面上的多个位置使用该数组。而不是global你应该使用static

 function get_job($name) 
 {
      static $people_jobs;

      if( !isset($people_jobs[$name]) || empty($people_jobs[$name]) )
      {
          $row = MySQL->Query("SELECT job FROM people WHERE name = $name");
          $people_jobs[$name] = $row->job;
      }

      return $people_jobs[$name];
}

无论您调用多少次,此函数都只会为一个人执行一次 MySQL 查询get_job($name);

于 2012-11-17T09:10:48.770 回答
0

这是典型的n + 1 问题,您进行 1 次查询以获取“人员”列表,然后为每个人进行一次查询以获取“工作”。

取决于它们是如何相关的..也许你可以使用一个查询来获得两者。例如:如果关系是 Nx1(1 人有 1 份工作,1 份工作可用于 N 人),那么您的初始查询应该类似于:

SELECT p.name, j.job FROM Person p INNER JOIN Job j ON (p.job_id = j.id) 

如果关系是 NxN,它会变得棘手:P,

希望这可以帮助

于 2012-11-17T09:46:33.643 回答