2012-04-07 114 views
0

我正在寫在那裏,用戶可以搜索基於各種標準(例如,作者,標題,出版商等)使用CodeIgniter庫搜索引擎。所以,我定義的接口BookSearch該負責搜索數據庫中的所有類都將實施OOP抽象與笨模型

interface BookSearch{ 
/** 
Returns all the books based on a given criteria as a query result. 
*/ 
public function search($search_query); 
} 

如果我要實現基於作者的搜索,我可以寫他類AuthorSearch作爲

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_query)。但是因爲我把搜索​​類的類名稱作爲字符串,所以我不能真的做到$this->$search_method->search($search_query)對不對?

如果這是在Java中,我會加載對象到我的常量。我知道PHP5有類型提示,但該項目的目標平臺具有PHP4。而且,我正在尋找更多的「CodeIgniter」來進行抽象。任何提示?

回答

1

你能真正做到$this->$search_method->search($search_query)。同樣在CI中,您可以根據需要指定庫名稱。

public function display($search_method, $search_query){ 
    $this->load->model($search_method, 'currentSearchModel'); 
    $this->currentSearchModel->search($search_query); 
} 
1

你說的是驅動模型。你可以,事實上,做你所建議不能做:

<?php 
$this->{$search_method}->search($search_query); 

CI有CI_Driver_Library & CI_Driver類來做到這一點(見CodeIgniter Drivers)。

然而,我發現,它通常是容易實現的接口/擴展一個抽象類,像你這樣做。繼承比CI的驅動更好。