为了减少查询的数量,当我从数据库中选择一些东西时,我想要启动最好的查询,它可以是以下之一:
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个查询,因为我已经有了来自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");
}
}
是正确的吗?我做得对吗?
例如,我可以像这样创建"Address"的构造函数:<?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
}
}
实际上现在我认为构造函数应该在一个单独的类,但无论如何…
一般说话……关于这个论点我能读到什么?欢迎阅读书籍、教程
希望我已经说清楚了,我的英语很糟糕…非常感谢你提前:)
是否存在一个实例,其中Address类将被调用,而City类将尚未被调用?如果没有,那么您可以用Address类扩展City类,您可以在Address类中访问来自City类的变量,因此只需将其更改为。然后,一旦City类从数据库中获取了信息,并将其分配给各种变量,那么它们就可以从Address类中访问。
class Address extends City {