我正在學習Code Igniter,並且作爲我的第一個項目,我正在重寫CI中的現有站點。
在現有網站上,所有動態或靜態頁面均使用PHP include來加載sidebar.php,該頁面從數據庫的類別表中填充。
<div id="sidebar">
<?php
$result = mysql_query('SELECT category_id, name, url FROM categories ORDER BY category_id ASC');
while ($row = mysql_fetch_array($result)) {
$name=$row['name'];
$url=$row['url'];
print "<p><a href=\"category/$url\">$name</a></p>";
}
?>
</div>
所以,現在我在CI開始,我計算過,要走的路是使與數據庫調用,一個側欄控制器,側邊欄視圖欄模型,然後加載在這個視圖默認頁面控制器。
因此,在/應用/型號我在應用中得到了sidebar_model.php
<?php
class Sidebar_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_categories()
{
$query = $this->db->get('categories');
return $query->result();
}
}
然後/控制器存在的sidebar.php
<?php
class Sidebar extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->model('sidebar_model');
$data['result'] = $this->sidebar_model->get_categories();
$this->load->view('templates/sidebar_view', $data);
}
}
然後在應用程序/視圖/模板有sidebar_view.php
<div id="sidebar">
<?php foreach($result as $row): ?>
<p><?php echo $row['name'] ?></p>
<?php endforeach ?>
</div>
這是從我的主頁控制器調用 -
<?php
class Pages extends CI_Controller {
public function view($page = 'home')
{
if (! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/sidebar_view', $data);
$this->load->view('templates/footer', $data);
}
}
我有麻煩的是,雖然頁面控制器顯然是加載側邊欄視圖(盒與正確的CSS樣式顯示),它拋出了PHP錯誤。
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: result
Filename: templates/sidebar_view.php
Line Number: 2
任何人都可以在正確的方向指向我嗎?雖然只使用側邊欄的php include會很快捷,但它看起來並不像MVC的做事方式。
對於冗長的帖子道歉,並提前致謝!