如何在两个或多个实例之间共享JOIN的结果?

时间:2013-03-22 21:21:20

标签: php design-patterns

为了减少查询次数,当我从我的数据库中选择一些东西时,我想发布最好的一个,可以是其中之一:

1- SELECT ... FROM cities JOIN states ON city.stateID = state.stateID WHERE city.cityID = ...
2- SELECT ... FROM cities WHERE city.cityID = ...
3- SELECT ... FROM states WHERE state.stateID = ...

如果我执行第一个,我将不需要(可能)执行第二个查询,因为我已经拥有数据。

但是如何在两个或更多类实例之间共享单个连接查询的结果? 并且假设我必须首先使用第三个查询,因为我已经拥有3个数据,您将如何从代码中控制City实例的创建?

<?php

 class City
 {
      protected $state;

      function getState()
      {
           if(!$this->state)
                 $this->state = State::getByID($this->stateID);
           return $this->state;
      }

      // since i may already have (in the outer scope) the $state instance...
      // to avoid an unnecessary query (State::getByID()) i allow to set the state:
      function setState(State $state)
      {
           if($state->stateID == $this->stateID)
                $this->state = $state;
           else
                throw new Exception("This City doesn't belong to the given State");
      }
 }

这是对的吗?我做对了吗?

例如,我可以像这样创建“地址”的构造函数:

<?php

class Address
{
    const PREFETCH_CITY = 1;
    const PREFETCH_STATE = 2;
    const PREFETCH_ALL = 3;

    construct($cityID, $prefetch = 0)
    {
         if($prefetch & static::PREFETCH_CITY)
              // i use the "JOIN cities" query (i also set $this->city)
         elseif($prefetch & static::PREFETCH_STATE)
              // i use the "JOIN states" query (i also set $this->state)
         elseif($prefetch & static::PREFETCH_ALL)
              // i use the "JOIN states JOIN cities" query
              // (i preset also both $this->city and $this->state)
         else
              // i don't use any JOIN, i just get the city
    }
}

实际上现在我认为构造函数应该在一个单独的类中,但无论如何......

一般都在说......我能读到这个论点吗?书籍,欢迎教程

希望很清楚,我的英语很可怕......非常感谢你提前:)

1 个答案:

答案 0 :(得分:0)

是否有一个实例会调用Address类并且City类不会被调用?如果没有,那么您可以使用Address类扩展City类,您可以从Address类中的City类访问变量,因此只需将其更改为。然后,一旦City类从数据库中获取信息,并将其分配给各种变量,那么可以从Address类访问它们。

class Address extends City {