introduction to mvc of codeigniter 2.1.x

80
CodeIgniter 基礎介紹 吳柏毅 Bo-Yi Wu 2012.02.11 http://blog.wu-boy.com/

Upload: bo-yi-wu

Post on 20-Aug-2015

17.847 views

Category:

Education


4 download

TRANSCRIPT

Page 1: Introduction to MVC of CodeIgniter 2.1.x

CodeIgniter基礎介紹

吳柏毅 Bo-Yi Wu2012.02.11

http://blog.wu-boy.com/

Page 2: Introduction to MVC of CodeIgniter 2.1.x

2

今天如果任何問題

請直接打斷講課過程

Page 3: Introduction to MVC of CodeIgniter 2.1.x

3

大家都會有個疑問又不是 PHP功能寫不出來為什麼要多學一套 Framework

(都直接硬幹 ...寫 Code)

Page 4: Introduction to MVC of CodeIgniter 2.1.x

4

為什麼使用 PHP Framework

● 團隊合作 (不管是公司或者是 Soho)– Coding Style (Code不會亂寫 )

– 目錄結構 (檔案不會亂放 ?)

● 快速開發 (站在巨人的肩膀上寫 Code)– 一堆內建功能模組

● 分頁 ,驗證碼 ,多國語言 ...

– 網路上一堆 Plugin(大家很熱心 )● SMS,Twitter,Youtube,Template,Plurk .. API

– 安全性高 (Open Source好處 )

– 程式碼更精短 (下一頁解說 )

Page 5: Introduction to MVC of CodeIgniter 2.1.x

5

過去都是這樣

$user = (isset($_GET['user'])) ? $_GET['user']:$_POST['user'];

Framework寫法$user = $this->input->get_post('user', true);

Framework寫法$user = $this->input->get_post('user', true);

過慮 XSS及 SQL Injection

Page 6: Introduction to MVC of CodeIgniter 2.1.x

6

過去的網站

公司網站公司網站

最新消息最新消息

關於我們關於我們

產品資訊產品資訊

聯絡我們聯絡我們

News.php

About.php

Product.php

Contact.php

Page 7: Introduction to MVC of CodeIgniter 2.1.x

7

新聞模組設計

News.php

新增新聞新增新聞

刪除新聞刪除新聞

修改新聞修改新聞

Add

Delete

Edit

news.php?mode=[add|delete|edit]&news_id=xxxx

MySQL

Page 8: Introduction to MVC of CodeIgniter 2.1.x

8

$action = (isset($_GET['mode'])) ? $_GET['mode'] : 'add';

switch($action)

{

case 'add':echo 'add news';$sql = “insert into xxxx values('aa', 'bb')”;

case 'edit':echo 'edit news';$sql = 'update xxx set xxxx where id = “1”';

case 'delete':echo 'delete news';$sql = 'delete xxx where id = “1”';

}

Page 9: Introduction to MVC of CodeIgniter 2.1.x

9

以前的作法

● CSS, Html, Javascript, PHP全部寫在一起– 系統漏洞

– 維護困難

– 擴充性差

– 多人開發

– 開發速度慢

Page 10: Introduction to MVC of CodeIgniter 2.1.x

10

共同開發困難最大原因是

每個人 Coding Style不同

Page 11: Introduction to MVC of CodeIgniter 2.1.x

11

為了解決程式設計師共同問題維護套件,快速閱讀程式碼所以 PHP Framework誕生

Why use PHP Framework?

Page 12: Introduction to MVC of CodeIgniter 2.1.x

12

使用 Framework設計

Page 13: Introduction to MVC of CodeIgniter 2.1.x

13

class News { punlic function __construct() {} public function add() {} public function edit($news_id) {} public function delete($news_id) {}}

PHP物件導向

Page 14: Introduction to MVC of CodeIgniter 2.1.x

14

太多 PHP Framework

Page 15: Introduction to MVC of CodeIgniter 2.1.x

15

這麼多套 PHP Framework為什麼最後選擇用

CodeIgniter

Page 16: Introduction to MVC of CodeIgniter 2.1.x

16

初學者必用 CodeIgniter

● 無敵懶人安裝 (好安裝 ,好移轉 )● 簡單目錄架構 (容易了解原始碼 )● 基礎MVC架構 (日後可跳其他 Framework)

● 高效能

– 上網搜尋即可發現分數及評價都非常高

Page 17: Introduction to MVC of CodeIgniter 2.1.x

17

最後還有最重要的一項

Page 18: Introduction to MVC of CodeIgniter 2.1.x

18

台灣程式設計師最大問題

Page 19: Introduction to MVC of CodeIgniter 2.1.x

19

不喜歡看英文文件

Page 20: Introduction to MVC of CodeIgniter 2.1.x

20

CodeIgniter繁體中文教學文件不必怕看不懂 (都是中文 )不必怕解決不了問題 (有論壇 )

Page 21: Introduction to MVC of CodeIgniter 2.1.x

21

What is CodeIgniter ?

Open Source Web Application Framework

MVC (Model View Controller) Architecture

Page 22: Introduction to MVC of CodeIgniter 2.1.x

22

WEB SERVER

ROUTES

Controller

ViewMODEL

LAYOUTDatabase

Client BROWSER

MVC Architecture

Page 23: Introduction to MVC of CodeIgniter 2.1.x

23

MVCView (views/product.php)

<html><body><p>Product Count:<?=$count?></p></body></html>

Controller (controllers/product.php)function showProduct($id) { $this->load->model(“product”); $count = $this->product->getCount($id); $data[‘count’] = $count; $this->load->view(“product”, $data);}

Model (controllers/product.php)function getCount($id) { $this->db->where(“id”, $id); $this->db->from(“my_product”); $query = $this->db->get(); return $this->num_rows();}

View

Controller

Model

Page 24: Introduction to MVC of CodeIgniter 2.1.x

24

安裝 CodeIgniter

● Windows(5分鐘安裝完成 )– 下載 CI原始 Zip檔案

– 解壓縮到網頁根目錄

● Linux– 安裝 Apache PHP MySQL

● Ubuntu, Debian 透過 apt● FreeBSD透過 ports

Page 25: Introduction to MVC of CodeIgniter 2.1.x

25

懶人安裝包

Windows+Appserv+CodeIgniter 2.1.0

下載 +解壓縮 =100%

Windwos安裝

Page 26: Introduction to MVC of CodeIgniter 2.1.x

26

完成畫面

Page 27: Introduction to MVC of CodeIgniter 2.1.x

27

作業一

● 在自己電腦架設 CodeIgniter 2.1.0● 設定 Virtual Host對應 CI目錄● 打開網址 http://ci.localhost/看到歡迎畫面● 進階作業

– 在 github開新的 Repository

– 將 CI原始碼 push到 github

Page 28: Introduction to MVC of CodeIgniter 2.1.x

28

Application Flow Of CodeIgniter

Page 29: Introduction to MVC of CodeIgniter 2.1.x

29

CodeIgniter架構

application– 網站所有資料

system– CodeIgniter核心目錄

user_guide– 說明文件

index.php (網站 index)

Page 30: Introduction to MVC of CodeIgniter 2.1.x

30

根目錄 index.php

● $system_path– 核心目錄

● $application_folder– 專案網站目錄

Page 31: Introduction to MVC of CodeIgniter 2.1.x

31

CodeIgniter application目錄● cache(快取檔案目錄 )

● config(網站設定檔 )

● controllers(控制器 )

● core(擴充核心目錄 )

● errors(404,403網頁 )

● helpers(擴充 helper核心 )

● libraries(網站模組 )

● models(Database檔案 )● views(前端 js,html檔案 )

Page 32: Introduction to MVC of CodeIgniter 2.1.x

32

CodeIgniter URL介紹

● example.com/index.php/class/function/ID– 控制器 (controller)啟動的類別 (class)

– 類別的函數 (function)被呼叫使用

– 任何變數要傳遞給控制器 (controller)所使用

example.com/news.php?mode=edit&id=10

Page 33: Introduction to MVC of CodeIgniter 2.1.x

33

移除網址列 index.php

● Apache mod_rewrite module– 利用 .htaccess移除 URL 包含的 index.php

RewriteEngine onRewriteBase /RewriteCond $1 !^(index\.php|assets|robots\.txt|$)RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Page 34: Introduction to MVC of CodeIgniter 2.1.x

34

加入副檔名 (小技巧 )

example/index.php/products/view/shoes.htm

修改設定檔 application/config/config.php$config['url_suffix'] = '.htm';

Page 35: Introduction to MVC of CodeIgniter 2.1.x

35

Controller(控制器 )

● 控制器 (Controller) 簡單來說就是 class 檔案● 放置目錄 application/controllers/

Page 36: Introduction to MVC of CodeIgniter 2.1.x

36

撰寫 Hello World

<?php

class Blog extends CI_Controller {

public function index()

{

echo 'Hello World!';

}

}

?>example.com/index.php/blog/index

Page 37: Introduction to MVC of CodeIgniter 2.1.x

37

加入 URL參數

<?php

class Blog extends CI_Controller {

public function edit($blog_id)

{

echo $blog_id;

}

}

?>example.com/index.php/blog/edit/14

Page 38: Introduction to MVC of CodeIgniter 2.1.x

38

預設的控制器

● 開啟 application/config/routes.php– $route['default_controller'] = 'blog';

Page 39: Introduction to MVC of CodeIgniter 2.1.x

39

物件導向基礎 (私有函數 )

● Public● Protected● Private

private function _utility(){ // do some code}

大家可以透過瀏覽器看看

Page 40: Introduction to MVC of CodeIgniter 2.1.x

40

類別建構子

<?phpclass Blog extends CI_Controller {

public function __construct(){

parent::__construct(); // Your own constructor code

$this->load->helper('url');$this->load->library('email');

}}?>

Page 41: Introduction to MVC of CodeIgniter 2.1.x

41

Default Controller

● example.com/index.php/welcome/index● example.com/

● 修改設定檔

– application/config/routes.php

– $route['default_controller'] = 'welcome';

Page 42: Introduction to MVC of CodeIgniter 2.1.x

42

作業二● 新增 Controller News

– 包含 3個method: add, delete, edit

– 將預設 controller改成 news● 移除網址 index.php

● add method

– 傳入 $title,$comment● delete method

– 傳入 $news_id● edit method

– 傳入 $news_id,$title,$comment● 加分作業 :開新 git branch並且 push

Page 43: Introduction to MVC of CodeIgniter 2.1.x

43

CodeIgniter View

● 目錄 application/views/● 可以任意將 html放入上述目錄中

Page 44: Introduction to MVC of CodeIgniter 2.1.x

44

如何載入 View

● 格式 $this->load->view('file_name');● 格式 $this->load->view('folder/file_name');

<?phpclass Blog extends CI_Controller {

function index(){

$this->load->view('blogview');}

}?>

Page 45: Introduction to MVC of CodeIgniter 2.1.x

45

新增動態資料到 View

● 格式 $this->load->view('file_name',$data);

$data = array( 'title' => 'My Title', 'heading' => 'My Heading', 'message' => 'My Message' );

$this->load->view('blogview', $data);

Page 46: Introduction to MVC of CodeIgniter 2.1.x

46

Views顯示資料

● 顯示格式如下

<html><head><title><?php echo $title;?></title></head><body>

<h1><?php echo $heading;?></h1><hr><div><?php echo $message;?></div>

</body></html>

Page 47: Introduction to MVC of CodeIgniter 2.1.x

47

迴圈用法● Controller主程式

<?phpclass Blog extends CI_Controller {

function index(){

$data['todo_list'] = array('1', '2', '3', '4');$data['title'] = "My Real Title";$data['heading'] = "My Real Heading";$this->load->view('blogview', $data);

}}?>

Page 48: Introduction to MVC of CodeIgniter 2.1.x

48

<html><head>

<title><?php echo $title;?></title></head><body>

<h1><?php echo $heading;?></h1><h3>My Todo List</h3><ul><?php foreach($todo_list as $item):?>

<li><?php echo $item;?></li><?php endforeach;?></ul>

</body></html>

Page 49: Introduction to MVC of CodeIgniter 2.1.x

49

將 views內容存到變數

● 格式 $this->load->view('file_name',$data, true);● 範例如下 :

– $output = $this->load->view('myfile', $data, true);

– echo $output;

Page 50: Introduction to MVC of CodeIgniter 2.1.x

50

作業三

● 將作業二輸出部份全部轉移到 views● 將網頁設計多重 view

– 包含 header,footer,menu,content

Page 51: Introduction to MVC of CodeIgniter 2.1.x

51

CodeIgniter Library and helper

● Library– 它就是 Class集合

● Helper– 它就是 function集合

● 載入 Library類別– $this->load->library('email');

● 載入 Helper輔助函數– $this->load->helper('url');

Page 52: Introduction to MVC of CodeIgniter 2.1.x

52

使用 Input Library

● POST, GET,COOKIE,或 SERVER 資料– $this->input->post('name')

– $this->input->get('name')

– $this->input->cookie('name')

– $this->input->server('name')

● 取得 POST或 GET資料– $this->input->get_post('name')

● 第 2參數設定為 true防止 xss攻擊 (過濾 )– $this->input->get_post('name',true)

Page 53: Introduction to MVC of CodeIgniter 2.1.x

53

使用 Input Library

● $this->input->ip_address()– 目前使用者 IP Address

● $this->input->valid_ip($ip)– 驗證 IP是否合法

● $this->input->user_agent()– 目前使用者瀏覽器資訊

● $this->input->is_ajax_request()– 判斷是否是 AJAX request

Page 54: Introduction to MVC of CodeIgniter 2.1.x

54

作業四

● 寫一個 Form包含 title,author,comment欄位● 送出後顯示在另外網頁或同一頁

Page 55: Introduction to MVC of CodeIgniter 2.1.x

55

CodeIgniter Models

● 目錄 : application/models/● application/models/user_model.php

class User_model extends CI_Model {

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

Page 56: Introduction to MVC of CodeIgniter 2.1.x

56

簡單model寫法class Blog_model extends CI_Model { function __construct() { // Model建構函數 parent::__construct(); } function get_last_ten_entries() { …............ } function insert_entry() { …............... }}

Page 57: Introduction to MVC of CodeIgniter 2.1.x

57

載入Model

● 格式 $this->load->model('Model_name');● 範例

– $this->load->model('Model_name');

– $this->Model_name->function();

● 重新命名物件

– $this->load->model('Model_name','fubar');

– $this->fubar->function();

Page 58: Introduction to MVC of CodeIgniter 2.1.x

58

controller+model+viewclass Blog_controller extends CI_Controller {

function index()

{

$this->load->model('blog_model');

$data['query'] = $this->blog_model->get_news();

$this->load->view('blog',$data);

}

}

Page 59: Introduction to MVC of CodeIgniter 2.1.x

59

連接資料庫

● 修改 application/config/database.php– $db['default']['hostname'] = 'localhost';

– $db['default']['username'] = 'XXXXXX';

– $db['default']['password'] = 'XXXXXX';

– $db['default']['database'] = 'XXXXXX';

– $db['default']['dbdriver'] = 'mysql';

Page 60: Introduction to MVC of CodeIgniter 2.1.x

60

快速入門$query = $this->db->query("YOUR QUERY");

if ($query->num_rows() > 0)

{

foreach ($query->result() as $row)

{

echo $row->title;

echo $row->name;

}

}

Page 61: Introduction to MVC of CodeIgniter 2.1.x

61

Database Active Record

● 查詢資料 (Selecting)

● 新增資料 (Inserting)

● 更新資料 (Updating)

● 刪除資料 (Deleting)

Page 62: Introduction to MVC of CodeIgniter 2.1.x

62

Active Record(Insert)$data = array(

'title' => 'my title' ,'name' => 'my name' ,'date' => '2011.04.16'

);

$this->db->insert('table_name', $data);

產生 :INSERT INTO table_name (title, name, date) VALUES ('my title', 'my name', '2011.04.16')

Page 63: Introduction to MVC of CodeIgniter 2.1.x

63

作業五

● 請新增資料庫 your_database● 新增資料表 user

– user_id, user_name, user_company

● 新增資料表 news– news_id, user_id, news_title, news_message

● 新增兩個model,利用 Form傳職新增到資料庫

Page 64: Introduction to MVC of CodeIgniter 2.1.x

64

Active Record(Select)

● $query = $this->db->get('table_name');– 產生 :SELECT * FROM mytable

● $query = $this->db->get('mytable', 10, 20);– 產生 :SELECT * FROM mytable LIMIT 20, 10

Page 65: Introduction to MVC of CodeIgniter 2.1.x

65

● 利用 select + get查詢– $this->db->select('title, content, date');

– $query = $this->db->get('mytable');

● 利用 select + from + get查詢– $this->db->select('title, content, date');

– $this->db->from('mytable');

– $query = $this->db->get();● SELECT title, content, date FROM mytable

● 加上判斷條件 where– $this->db->where('name', $name);

– $this->db->where('title', $title);

– $this->db->where('status', $status);

Page 66: Introduction to MVC of CodeIgniter 2.1.x

66

回傳查詢值 (Result)

● 多筆資料 (常用 )– result()物件

– result_array()陣列

● 單筆資料

– row()物件

– row_array()陣列

Page 67: Introduction to MVC of CodeIgniter 2.1.x

67

資料顯示 (物件 )

$query = $this->db->query("YOUR QUERY");if ($query->num_rows() > 0){

foreach ($query->result() as $row){

echo $row->title;echo $row->name;echo $row->body;

}}

Page 68: Introduction to MVC of CodeIgniter 2.1.x

68

顯示資料 (陣列 )

$query = $this->db->query("YOUR QUERY");

if ($query->num_rows() > 0){

foreach ($query->result_array() as $row){

echo $row['title'];echo $row['name'];echo $row['body'];

}}

Page 69: Introduction to MVC of CodeIgniter 2.1.x

69

作業六

● 將 user及 news資料表內容顯示出來– 新增 user_model及 new_model獨立method

– 將資料顯示在 view

Page 70: Introduction to MVC of CodeIgniter 2.1.x

70

Active Record(Update)

$data = array('title' => $title,'name' => $name,'date' => $date

);

$this->db->where('id', $id);$this->db->update('mytable', $data);

產生 : UPDATE mytable SET title = '{$title}', name = '{$name}', date = '{$date}' WHERE id = $id

Page 71: Introduction to MVC of CodeIgniter 2.1.x

71

作業七

● user及 news資料表編輯功能– 在 views顯示編輯按鈕

– 點選後將該比資料帶入到 Form

– 按下送出更新該筆資料後並回到 list頁面

Page 72: Introduction to MVC of CodeIgniter 2.1.x

72

Active Record(Delete)

● $this->db->where('id', $id);● $this->db->delete('mytable');

– DELETE FROM mytable WHERE id = $id

Page 73: Introduction to MVC of CodeIgniter 2.1.x

73

作業八

● user及 news資料表刪除功能– 在列表顯示刪除按鈕

– 點選後提示是否刪除該筆資料

– 按下確定後刪除資料並回到 list頁面

Page 74: Introduction to MVC of CodeIgniter 2.1.x

74

Active Record(join表格 )

$this->db->select('*');$this->db->from('blogs');$this->db->join('comments', 'comments.id = blogs.id', 'left');$query = $this->db->get();

產生 :SELECT * FROM blogs LEFT JOIN comments ON comments.id = blogs.id

Page 75: Introduction to MVC of CodeIgniter 2.1.x

75

作業九

● Join兩資料表 user及 news並顯示– 左邊選單 :

● 發表新聞● 新增作者

● 新聞列表 (檢視 ,更新 ,刪除 )● 作者列表 (檢視 ,更新 ,刪除 )

Page 76: Introduction to MVC of CodeIgniter 2.1.x

76

CodeIgniter command line

● 透過 command去執行 cron-job● $this->input->is_cli_request()

– 判斷瀏覽器是否可以執行

● 動態改變權限、清除 cache目錄、執行備份

● 整合其他語言 (Perl,Python..)

Page 77: Introduction to MVC of CodeIgniter 2.1.x

77

使用方式

php index.php Controller function

php index.php tools message

Page 78: Introduction to MVC of CodeIgniter 2.1.x

78

CodeIgniter Cache快取

● 在 controller任何地方都可以加入– $this->output->cache(n);

– n代表分鐘

– 只有在 $this->load->view('name');做用

● cache目錄預設在 application/cache

● 可以在 application/config/config.php更改路徑

● 更改 application/cache權限 (Apache使用者 )

Page 79: Introduction to MVC of CodeIgniter 2.1.x

79

今天課程就到這裡

大家有沒有任何問題

http://www.codeigniter.org.tw/forum/

Page 80: Introduction to MVC of CodeIgniter 2.1.x

80

參考資料

● CodeIgniter 使用手冊版本 2.1.0– http://codeigniter.org.tw/user_guide/

● 部落格技術教學

– http://blog.wu-boy.com/tag/codeigniter/