Php 使用CodeIgniter模型的OOP抽象
我正在编写一个图书馆搜索引擎,用户可以使用CodeIgniter根据各种标准(例如,作者、标题、出版商等)进行搜索。因此,我定义了接口Php 使用CodeIgniter模型的OOP抽象,php,codeigniter,Php,Codeigniter,我正在编写一个图书馆搜索引擎,用户可以使用CodeIgniter根据各种标准(例如,作者、标题、出版商等)进行搜索。因此,我定义了接口BookSearch,所有负责搜索数据库的类都将实现该接口 interface BookSearch{ /** Returns all the books based on a given criteria as a query result. */ public function search($search_query); } 如果我想实现基于作者的搜索,我
BookSearch
,所有负责搜索数据库的类都将实现该接口
interface BookSearch{
/**
Returns all the books based on a given criteria as a query result.
*/
public function search($search_query);
}
如果我想实现基于作者的搜索,我可以将classAuthorSearch
编写为
class AuthorSearch implements BookSearch extends CI_Model{
function __construct(){
parent::__construct();
}
public function search($authorname){
//Implement search function here...
//Return query result which we can display via foreach
}
}
现在,我定义了一个控制器来利用这些类并显示结果
class Search extends CI_Controller{
/**
These constants will contain the class names of the models
which will carry out the search. Pass as $search_method.
*/
const AUTHOR = "AuthorSearch";
const TITLE = "TitleSearch";
const PUBLISHER = "PublisherSearch";
public function display($search_method, $search_query){
$this->load->model($search_method);
}
}
这就是我的问题所在。CodeIgniter手册说,要调用模型中的方法(即,search
),我需要编写$this->AuthorSearch->search($search\u query)
。但是由于我将搜索类的类名作为字符串,所以我不能真正执行$this->$search\u method->search($search\u query)
对吗
如果这是在Java中,我会将对象加载到我的常量中。我知道PHP5有类型暗示,但是这个项目的目标平台有PHP4。而且,我正在寻找一种更“CodeIgniter”的方法来完成这个抽象。有什么提示吗?你真的可以做
$this->$search\u method->search($search\u query)
。在CI中,还可以根据需要指定库名称
public function display($search_method, $search_query){
$this->load->model($search_method, 'currentSearchModel');
$this->currentSearchModel->search($search_query);
}
你说的是驾驶员模型。事实上,你可以做你建议做不到的事:
<?php
$this->{$search_method}->search($search_query);