我知道不能在 php 的类中定义一个类,但是我很好奇是否有另一种方法可以达到预期的效果。
我目前有一组 3 个用于进行搜索的对象。第一个称为 $search_request。它包含 $keywords (string)、$search_results_per_page (int)、$page_requested (int)、$owner_id (int) 等属性
我还有一个名为 $search_result 的对象,它包含 $total_matches (int)、$result_set(对象数组)等属性
最后,我得到了包含 $search_request 和 $search_result 的 $search_handler 对象,以及基于 $search_request 构建 $search_result 的函数。用法是这样的:
$search_handler = new search_handler();
$search_handler->search_request->keywords = "cats, dogs";
$search_handler->search_request->search_results_per_page = 10;
$search_handler->search_request->page_search_requested = 1;
$search_handler->get_search_result();
echo $search_handler->search_result->total_matches;
foreach($search_handler->search_result->result_set)
{
//do something
}
所有这一切都很好。问题是我想为不同的对象重复这个模型,所以目前我不得不在每个类上使用“search_”前缀的 hackey 解决方案。
我想要类似的东西:
class search
{
public class request
{
$keywords = "";
$search_results_per_page = 5;
$page_requested = 1;
}
public class result
{
$total_matches = null;
$result_set = array();
}
public get_results()
{
//check cache first
$cached = look_in_cache(md5(serialize($this->request)));
if($cached)
{
$this->result->result_set = $cached;
$count = count($cached);
$this->result->total_matches = $count;
}
else
{
//look in db
$results = get_results_from_database($this->request->keywords); //db call goes here
$this->result->result_set = $results;
$count = count($results);
$this->result->total_matches = $count;
}
}
}
//usage
$search = new search();
$search->request->keywords = "cats, dogs";
$search->request->search_results_per_page = 10;
$search->request->page_search_requested = 1;
$search->get_results();
echo $search->results->total_matches;
foreach($search->results->result_set as $result)
{
//do something
}