CodeIgnitor是我在2013年接觸到的PHP框架,
我很喜歡他的簡單輕量化,很好佈署,
可以快速開發一個簡單的網站,實作你的Prototype。
首先,先要有apache的環境
此範例是用 usbwebserver
再到官網下載CodeIgnitor 3,
解壓縮到你的開發環境,就可以看到首頁的畫面,
使用Visual Studio Code 可以看到完整的目錄結構如下:
新增一個hello function
可以得到以下的結果
預設的路由很不好看,對吧,
所以通常第一件事情就是這個規則改掉,
新增.htaccess
在整個專案的根目錄增加.htaccess
此例中的架構如下
- AppServ/www/account
- application/
- system/
- index.php
.htaccess
在.htaccess輸入以下內容
RewriteEngine on RewriteBase / RewriteCond $1 !^(index\.php|images|swf|uploads|js|css|assets|robots\.txt|$) RewriteRule ^(.*)$ /ci/index.php/$1 [L,QSA]
可以發現網址變得簡潔了
新增Controller
在controllers資料夾,接新增一個.php檔案,如Product.php
繼承自CI_controller
defined('BASEPATH') OR exit('No direct script access allowed'); class Product extends CI_Controller { public function index() { echo "Show all products"; } public function Detail(){ echo "Sowe Product detail"; } }
新增View
在views資料夾,新增一個product_view.php檔案
defined('BASEPATH') OR exit('No direct script access allowed'); class Product extends CI_Controller { public function index() { $this->load->view("product_view"); } public function Detail(){ echo "Sowe Product detail"; } }
增加動態資料到 View
defined('BASEPATH') OR exit('No direct script access allowed'); class Product extends CI_Controller { public function index() { $data = array( 'title' => 'My Product', 'name' => '產品名稱', 'product_no'=>'產品編號' ); $this->load->view('product_view',$data); } }
就可以輕鬆將資料帶出給view
建立物件,載入物件
在library資料夾新增物件

在controller 調用物件,$this->load->library(‘物件名稱’);


AutoLoad機制
如果嫌每次都要打
$this->load->library(‘物件名稱’); 很麻煩
可以開啟config/autoload.php 將物件名稱加入到對應的資料夾的array中
$autoload[‘libraries’] = array(‘Car’);
