【问题标题】:OOP abstraction with CodeIgniter Models使用 CodeIgniter 模型进行 OOP 抽象
【发布时间】:2012-04-07 08:35:22
【问题描述】:

我正在编写一个库搜索引擎,用户可以使用 CodeIgniter 根据各种条件(例如作者、标题、出版商等)进行搜索。因此,我定义了接口BookSearch,所有负责搜索数据库的类都将实现该接口

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

如果我想实现基于作者的搜索,我可以将他的 class 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”的方式来进行这种抽象。有什么提示吗?

【问题讨论】:

    标签: php 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);
    }
    

    【讨论】:

      【解决方案2】:

      您所说的是驱动程序模型。事实上,你可以做你建议做不到的事情:

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

      CodeIgniter 有 CI_Driver_LibraryCI_Driver 类来执行此操作(请参阅 CodeIgniter Drivers)。

      但是,我发现实现接口/扩展抽象类通常更简单,就像您正在做的那样。继承比 CI 的驱动更好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-16
        • 2014-07-19
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多