php – Joomla! – 為什麼不在 view.html.php 使用 Model 呢?

因為要使用 Model 讀寫資料庫的時候,不見得會有 View 的需求,所以將 Model 初始化等等相關的自動程序,寫在 Controller 的話,可以節省重複性的程式碼片段。

例如在 controllers/xxx.phbp

function __construct()
{
    parent::__construct();

    // 讓這裡的任何 method 都可以直接使用 model
    $this->model_store = $this->getModel('store');
}

// 首頁取得資料後顯示在 view
public function index()
{
    $this->model_store->getAll();
}

// 僅處理儲存的數據後跳轉,並不需要到 view
public function save()
{
    $this->model_store->save();
}

 

發表迴響