在 CI 如果我們要在頁面裡讀入一樣的區塊內容,可以透過共用一個 view 的檔案來達成,但如果這個區塊內容有包含資料庫的連結,我們就可以使用 library 來處理達成我們的需求。

首先在 application/libraries 的資料夾內,建一個新的 library,我把它命名為 My_lib,內容如下:

defined('BASEPATH') OR exit('No direct script access allowed');

class My_lib {

    public function do_something()
    {
    }
}

如果要使用這個 library,就可以在 controller 內讀入:

$this->load->library('my_lib');

以上那段如果是要應用在整個 controller 內,可以將之寫在建構子內,讀入後就能使用先前設計的方法,比如我在方法裡加上這段:

class My_lib {

    public function do_something()
    {
        echo "hi";
    }
}

這樣在其他的地方,就可以像這樣使用:

$this->my_lib->do_something();

這樣頁面上就會出現 hi 的內容。

要在 library 內使用 model 讀取資料庫的話,可以像這麼做:

    public function __construct()
    {
        $this->ci =& get_instance();
        $this->ci->load->model('test_model', 'test_m');
    }

    public function do_something()
    {
        return $this->ci->test_m->getList();
    }

如果要使用 view 的話也是要透過 $this->ci

public function board()
    {
        $data["users"] = $this->ci->general_m->getList();
        $this->ci->load->view('part/users', $data);
    }

 

把東西寫到 library,就不用每個頁面要用的時候都要在那個 controller 讀 model 了。