advanced introduction to codeigniter

115
CodeIgniter 進階應用 Bo-Yi Wu 吳柏毅 2012.02.18 http://blog.wu-boy.com/

Upload: bo-yi-wu

Post on 20-Aug-2015

7.522 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: advanced introduction to codeigniter

CodeIgniter進階應用

Bo-Yi Wu吳柏毅2012.02.18

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

Page 2: advanced introduction to codeigniter

Outline

如何善用使用 CodeIgniter內建函式庫 移植及撰寫個人 Library 擴充核心程式碼

GetSparks簡介

Page 3: advanced introduction to codeigniter

3

如何善用 CodeIgniter函式庫 ?

Page 4: advanced introduction to codeigniter

4

Loader Library系統自動初始化

Page 5: advanced introduction to codeigniter

5

$this->load->library('class', $config, 'object')

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

$this->email->some_function().

如何使用

Page 6: advanced introduction to codeigniter

6

同時載入多個函式庫

$this->load->library(array('email', 'table'));

Page 7: advanced introduction to codeigniter

7

傳入參數

$this->load->library('class', $config)

example: $this->load->library('email')

$config = array ( 'mailtype' => 'html', 'charset' => 'utf-8, 'priority' => '1');

Page 8: advanced introduction to codeigniter

8

public function __construct($config = array()){ if (count($config) > 0) { $this->initialize($config); }}

Library參數初始化

initialize為 class其中一個 function

Page 9: advanced introduction to codeigniter

9

指定物件名稱

$this->load->library('session', $config)$this->session->some_function()

$this->load->library('session', $config, 'my_sess')$this->my_sess->some_function()

Page 10: advanced introduction to codeigniter

10

Config Library系統自動初始化

Page 11: advanced introduction to codeigniter

11

系統自動讀取網站設定檔

(application/config/config.php)

Page 12: advanced introduction to codeigniter

12

將固定資料都存放在 config目錄

application/config/bitly.php

Page 13: advanced introduction to codeigniter

13

範例存放 API Key

<?php$config['user_name'] = 'appleboy';$config['api_key'] = 'xxxxxxxx';$config['format'] = 'json';?>

Page 14: advanced introduction to codeigniter

14

取得設定檔資料

$this->config->load('bitly');$this->config->item('api_key');

Page 15: advanced introduction to codeigniter

15

在這裡大家有沒有一個疑問假設載入兩個設定檔

Page 16: advanced introduction to codeigniter

16

application/config/bitly.php

application/config/tiny.php

<?php$config['user_name'] = 'appleboy';$config['api_key'] = 'api_key_01';$config['format'] = 'json';?>

<?php$config['user_name'] = 'appleboy46';$config['api_key'] = 'api_key_02';$config['format'] = 'xml';?>

Page 17: advanced introduction to codeigniter

17

$this->config->load('bitly');$this->config->load('tiny');

Page 18: advanced introduction to codeigniter

18

輸出資料會是 ?

$this->config->item('api_key');

答案 : api_key_02

Page 19: advanced introduction to codeigniter

19

為什麼資料變數會衝突呢 ?那該如何解決 ?

Page 20: advanced introduction to codeigniter

20

系統載入流程

檢查 application/config/目錄檔案是否存在 不存在 (continue) 存在 (include方式載入 )

後載入覆蓋前面設定檔

Page 21: advanced introduction to codeigniter

21

解決變數衝突

第二個參數設定為 true

$this->config->load('bitly', true);$this->config->load('tiny', true);

Page 22: advanced introduction to codeigniter

22

衝突讀取方式

加入第三參數

$this->config->item('api_key', 'bitly');$this->config->item('api_key', 'tiny');

Page 23: advanced introduction to codeigniter

23

另類解決方式

item key為什麼會出現衝突 ?item key為什麼會出現衝突 ?

Page 24: advanced introduction to codeigniter

24

Web程式設計師對變數命名方式大不同

(資料庫欄位命名 )user_nameUserNameusername

Page 25: advanced introduction to codeigniter

25

改變 key命名方式prefix_name + item_name

Page 26: advanced introduction to codeigniter

26

application/config/bitly.php

application/config/tiny.php

<?php$config['bitly_user_name'] = 'appleboy';$config['bitly_api_key'] = 'api_key_01';$config['bitly_format'] = 'json';?>

<?php$config['tiny_user_name'] = 'appleboy46';$config['tiny_api_key'] = 'api_key_02';$config['tiny_format'] = 'xml';?>

Page 27: advanced introduction to codeigniter

27

此命名方式可以加速其他程式設計師閱讀程式碼方便性

Page 28: advanced introduction to codeigniter

28

作業一

新增 template設定檔 base_title site_keyword site_description

將設定檔內容讀出並載入到 layout

Page 29: advanced introduction to codeigniter

29

Email Library大量寄信

Page 30: advanced introduction to codeigniter

30

Email Class

多重收件人

副本 (CC)和密件副本 (BCCs) 支援 HTML或者是純文字 (Plaintext)郵件 附件檔案

Email Debugging tools

Page 31: advanced introduction to codeigniter

31

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

$this->email->from('[email protected]', 'Your Name');$this->email->to('[email protected]'); $this->email->cc('[email protected]'); $this->email->bcc('[email protected]');

$this->email->subject('Email Test');$this->email->message('Testing the email class.');

$this->email->send();

echo $this->email->print_debugger();

Page 32: advanced introduction to codeigniter

32

$this­>email­>to() $this­>email­>cc() $this­>email­>bcc()

可以帶入陣列或單一資料

$this­>email­>send()

if ( ! $this->email->send()){ echo $this->email->print_debugger();}

Page 33: advanced introduction to codeigniter

33

附件檔案

$this->email->attach('file_path')

$this->email->attach('/path/to/file01.zip');$this->email->attach('/path/to/file02.zip');$this->email->attach('/path/to/file03.zip');

$this->email->send();

Page 34: advanced introduction to codeigniter

34

File Uploading Library(多檔案上傳 )

Page 35: advanced introduction to codeigniter

35

檔案上傳流程

設定存放上傳目錄權限

調整 php.ini檔案上傳設定 建立上傳表單

驗證使用者上傳檔案

印出檔案訊息並且寫到資料庫

Page 36: advanced introduction to codeigniter

36

$config['upload_path'] = './uploads/';$config['allowed_types'] = 'gif|jpg|png';$config['max_size'] = '100';$config['max_width'] = '1024';$config['max_height'] = '768';

$this->load->library('upload', $config);

if ( ! $this->upload->do_upload('input_column_name')){ $error = array('error' => $this->upload->display_errors()); $this->load->view('upload_form', $error);}else{ $data = array('upload_data' => $this->upload->data()); $this->load->view('upload_success', $data);}

Page 37: advanced introduction to codeigniter

37

設定參數

upload_path(絕對或者是相對即可 ) allowed_types(可上傳類型用豎線 '|'分開 ) overwrite(相同檔名則覆蓋 ) max_size(檔案大小限制 ) max_width(圖片專用 ) max_height(圖片專用 ) encrypt_name(檔名加密字串取代 )

Page 38: advanced introduction to codeigniter

38

$this->upload->data()

[file_name] => mypic.jpg [file_type] => image/jpeg [file_path] => /path/to/your/upload/ [full_path] => /path/to/your/upload/jpg.jpg [raw_name] => mypic [orig_name] => mypic.jpg [file_ext] => .jpg [file_size] => 22.2 [is_image] => 1 [image_width] => 800 [image_height] => 600 [image_type] => jpeg [image_size_str] => width="800" height="200"

Page 39: advanced introduction to codeigniter

39

作業二

新增上傳表單 將上傳檔案資訊存入資料庫

並且將檔案以附件寄給該使用者

Page 40: advanced introduction to codeigniter

40

Form Validation Library表單驗證

Page 41: advanced introduction to codeigniter

41

欄位驗證

1. 欄位包含非法字元2.  欄位長度必須大於 minimum  3.  欄位長度必須小於 maximum4. 使用者名稱不能重複 (資料庫比對 )

Page 42: advanced introduction to codeigniter

42

Controller

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

if ($this->form_validation->run() == false){ $this->load->view('myform');}else{ $this->load->view('formsuccess');}

Page 43: advanced introduction to codeigniter

43

表單驗證規則

$this->form_validation->set_rules()

Page 44: advanced introduction to codeigniter

44

驗證規則 (註冊表單 )

$this->form_validation->set_rules('username', '帳號 ', 'required');$this->form_validation->set_rules('password', '密碼 ', 'required');$this->form_validation->set_rules('passconf', '確認 ', 'required');$this->form_validation->set_rules('email', '電子郵件 ', 'required');

Page 45: advanced introduction to codeigniter

45

Form Controller$this->load->library('form_validation');

$this->form_validation->set_rules('username', '帳號 ', 'required');$this->form_validation->set_rules('password', '密碼 ', 'required');$this->form_validation->set_rules('passconf', '確認密碼 ', 'required');$this->form_validation->set_rules('email', '電子郵件 ', 'required');

if ($this->form_validation->run() == FALSE){ $this->load->view('myform');}else{ $this->load->view('formsuccess');}

Page 46: advanced introduction to codeigniter

46

多重驗證規則

$this->form_validation->set_rules('username', '帳號 ', 'required|min_length[5]|max_length[12]|is_unique[users.username]');

$this->form_validation->set_rules('password', '密碼 ', 'required|matches[passconf]');

$this->form_validation->set_rules('passconf', '確認密碼 ', 'required');

$this->form_validation->set_rules('email', '電子郵件 ', 'required|valid_email|is_unique[users.email]');

Page 47: advanced introduction to codeigniter

47

事先處理欄位

$this->form_validation->set_rules('username', '帳號 ', 'trim|required|min_length[5]|max_length[12]|xss_clean');

$this->form_validation->set_rules('password', '密碼 ', 'trim|required|matches[passconf]|md5');

$this->form_validation->set_rules('passconf', '確認密碼 ', 'trim|required');

$this->form_validation->set_rules('email', '電子郵件 ', 'trim|required|valid_email|is_unique[users.email]');

htmlspecialchars, trim, MD5(native function) 皆可處理

Page 48: advanced introduction to codeigniter

48

記憶表單

欄位驗證失敗回到表單

顯示之前留下的資料

$this->load->helper('form')

set_value('username', 'appleboy')set_select('myselect', 'one', true)set_checkbox('mycheck[]', '1', true)set_radio('myradio', '1', true)

Page 49: advanced introduction to codeigniter

49

自行設計驗證函數

$this->form_validation->set_rules('username', '帳號 ', 'callback_username_check')

Page 50: advanced introduction to codeigniter

50

public function index(){ $this->load->library('form_validation'); $this->form_validation->set_rules('username', '帳號 ', 'callback_username_check'); $this->form_validation->set_rules('password', '密碼 ', 'required'); $this->form_validation->set_rules('passconf', '確認密碼 ', 'required'); $this->form_validation->set_rules('email', '電子郵件 ', 'required'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); }}

Page 51: advanced introduction to codeigniter

51

Call back function

public function username_check($str){ if ($str == 'test') { return FALSE; } else { return TRUE; }}

Page 52: advanced introduction to codeigniter

52

定義錯誤訊息

$this->form_validation->set_message('rule', 'error message')

Page 53: advanced introduction to codeigniter

53

錯誤訊息

全部顯示

<?php echo validation_errors(); ?>個別顯示

<?php echo form_error('file_name'); ?>

Page 54: advanced introduction to codeigniter

54

作業三

使用者註冊表單 欄位 :Email,密碼 ,確認密碼 撰寫 call back function確認帳號是否存在 自訂錯誤訊息

Page 55: advanced introduction to codeigniter

55

Image Manipulation Library(影像處理 )

Page 56: advanced introduction to codeigniter

56

影像處理 (GD vs ImageMagic)

修改尺寸

建立縮圖

圖片裁剪

圖片旋轉

浮水印

Page 57: advanced introduction to codeigniter

57

個人建議大量圖形網站用ImageMagic

(支援 command line 執行 )(獨立處理圖片 )

(不需要動到前端 Server)

Page 58: advanced introduction to codeigniter

58

如果公司經費許可

AWS S3雲端儲存服務Simple Storage Service

Page 59: advanced introduction to codeigniter

59

$this->load->library('image_lib')

初始化

Page 60: advanced introduction to codeigniter

60

處理影像

$config['image_library'] = 'gd2';$config['source_image'] = '/path/mypic.jpg';$config['create_thumb'] = true;$config['width'] = 75;$config['height'] = 50;

$this->load->library('image_lib', $config);

$this->image_lib->resize();

Page 61: advanced introduction to codeigniter

61

參數設定

image_library: GD, GD2, ImageMagick, NetPBM library_path: Linux, Windows底下路徑 source_image: 絕對 /相對路徑 new_image: 輸出檔案絕對 /相對路徑 width:圖片寬度 height:圖片高度 create_thumb:避免覆蓋原檔案

Page 62: advanced introduction to codeigniter

62

錯誤訊息

if ( ! $this->image_lib->resize()){ echo $this->image_lib->display_errors();}

Page 63: advanced introduction to codeigniter

63

影像處理函數

$this­>image_lib­>resize() $this­>image_lib­>crop() $this­>image_lib­>rotate() $this­>image_lib­>clear()

Page 64: advanced introduction to codeigniter

64

影像處理函數

$this­>image_lib­>resize() $this­>image_lib­>crop() $this­>image_lib­>rotate() $this­>image_lib­>clear()

Page 65: advanced introduction to codeigniter

65

務必設定

$config['create_thumb'] = true; $config['new_image'] = '/path/new_image.jpg';

避免原始檔案被處理 (保留原檔 )

Page 66: advanced introduction to codeigniter

66

影像處理函數

$this­>image_lib­>resize() $this­>image_lib­>crop() $this­>image_lib­>rotate() $this­>image_lib­>clear()

Page 67: advanced introduction to codeigniter

67

$config['image_library'] = 'imagemagick';$config['library_path'] = '/usr/local/bin';$config['source_image'] = '/path/to/mypic.jpg';$config['x_axis'] = '100';$config['y_axis'] = '60';

$this->image_lib->initialize($config);

if ( ! $this->image_lib->crop()){ echo $this->image_lib->display_errors();}

Page 68: advanced introduction to codeigniter

68

影像處理函數

$this­>image_lib­>resize() $this­>image_lib­>crop() $this­>image_lib­>rotate() $this­>image_lib­>clear()

Page 69: advanced introduction to codeigniter

69

$config['image_library'] = 'netpbm';$config['library_path'] = '/usr/bin/';$config['source_image'] = '/path/to/mypic.jpg';$config['rotation_angle'] = 'hor';

$this->image_lib->initialize($config);

if ( ! $this->image_lib->rotate()){ echo $this->image_lib->display_errors();}

Page 70: advanced introduction to codeigniter

70

rotation_angle參數

90(順時針 90度 ) 180(順時針 180度 ) 270(順時針 270度 ) hor(水平旋轉 ) vrt(垂直旋轉 )

Page 71: advanced introduction to codeigniter

71

影像處理函數

$this­>image_lib­>resize() $this­>image_lib­>crop() $this­>image_lib­>rotate() $this­>image_lib­>clear()

Page 72: advanced introduction to codeigniter

72

$this->image_lib->clear()重置所有設定項目

Page 73: advanced introduction to codeigniter

73

作業

增加使用者頭像上傳

限制上傳檔案型態 (jpeg,jpg,png,gif) 可以自訂圖像 (隨時更改 ) 製作縮圖顯示於使用者列表

Page 74: advanced introduction to codeigniter

74

Language Library(多國語系 )

Page 75: advanced introduction to codeigniter

75

兩個存放語系目錄

application/language/[english|zh­tw] system/language/[english|zh­tw] 先後讀取

application/config/config.php 設定預設語系

Page 76: advanced introduction to codeigniter

76

建立語言檔案

檔案命名方式

error_lang.php

內容以 $lang陣列方式表示 $lang['language_key'] = "我是中文 ";

Page 77: advanced introduction to codeigniter

77

$lang['error_email'] = "您必須填入電子郵件 ";$lang['error_url'] = "您必須填入完整網址 ";$lang['error_username'] = "您必須填入帳號名稱 ";

避免衝突

Page 78: advanced introduction to codeigniter

78

讀取語言檔案

$this->lang->load('filename', 'language')

Page 79: advanced introduction to codeigniter

79

讀取資料

Language helper函式

lang('language_key')

$this->load->helper('language');

Page 80: advanced introduction to codeigniter

80

作業

請用下列 URL切換中英文語系 index.php/controller/function?lang=zh­tw

Page 81: advanced introduction to codeigniter

81

Pagination Library(分頁處理 )

Page 82: advanced introduction to codeigniter

82

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

$config['base_url'] = '/index.php/test/page/';$config['total_rows'] = 200;$config['per_page'] = 20;

$this->pagination->initialize($config);

echo $this->pagination->create_links();

Page 83: advanced introduction to codeigniter

83

分頁參數

base_url:完整的 URL路徑 ,包含了控制器(controller)/函數 (function)

total_rows:總筆數 per_page:單頁顯示幾筆 uri_segment: URI哪個部份包含了頁數 num_links:您目前所在頁數前面跟後面所顯示的分頁數量

use_page_numbers:用 page number顯示

Page 84: advanced introduction to codeigniter

84

講了這麼多 CodeIgniter內建 Library那該如何撰寫屬於自己的套件呢

Page 85: advanced introduction to codeigniter

85

如果別人寫好的 Library該如何無痛導入到

CodeIgniter

Page 86: advanced introduction to codeigniter

86

注意事項

檔案命名

一律採用小寫命名 , 如 my_class.php

類別宣告

類別宣告第一個字母必須為大寫 ,如 class My_class

Page 87: advanced introduction to codeigniter

87

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Someclass {

public function some_function() { }}

/* End of file Someclass.php */

Page 88: advanced introduction to codeigniter

88

初始化類別傳遞參數

$params = array('type' => 'large', 'color' => 'red');

$this->load->library('someclass', $params);

Page 89: advanced introduction to codeigniter

89

public function __construct($config = array()){ If ( ! empty($config)) { $this->initialize($config); }}

Page 90: advanced introduction to codeigniter

90

在 Library裡該如何使用CodeIgniter其他資源呢 ?

Page 91: advanced introduction to codeigniter

91

$this->load->helper('url');$this->load->library('session');$this->config->item('base_url');

Page 92: advanced introduction to codeigniter

92

$this->_obj =& get_instance();

Page 93: advanced introduction to codeigniter

93

public function __construct(){ $this->_obj =& get_instance(); $this->_obj->load->config('google_url_api');}

Page 94: advanced introduction to codeigniter

94

作業

建立個人專用 Library 將 goo.gl php library導入

http://code.google.com/p/googl­php/

Page 95: advanced introduction to codeigniter

95

網站一定會有共同處理的地方(多國語系 )

(多重登入 Facebook,Google)

Page 96: advanced introduction to codeigniter

96

如果有 10個 Controller那不就 10個檔案都加上相同程式碼?

Page 97: advanced introduction to codeigniter

97

這時候就需要

擴充核心函式庫

Page 98: advanced introduction to codeigniter

98

class Welcome_01 extends CI_Controllerclass Welcome_02 extends CI_Controllerclass Welcome_03 extends CI_Controllerclass Welcome_04 extends CI_Controllerclass Welcome_05 extends CI_Controllerclass Welcome_06 extends CI_Controllerclass Welcome_07 extends CI_Controllerclass Welcome_08 extends CI_Controller

Controller都需要有共同的變數及函數

Page 99: advanced introduction to codeigniter

99

class Welcome_01 extends MY_Controllerclass Welcome_02 extends MY_Controllerclass Welcome_03 extends MY_Controllerclass Welcome_04 extends MY_Controllerclass Welcome_05 extends MY_Controllerclass Welcome_06 extends MY_Controllerclass Welcome_07 extends MY_Controllerclass Welcome_08 extends MY_Controller

更改變數及函數則大家一起變動

Page 100: advanced introduction to codeigniter

100

控制器 01

登入函式 登入函式 登入函式 登入函式登入函式

控制器 02 控制器 03 控制器 04 控制器 05

CI_Controller

Page 101: advanced introduction to codeigniter

101

控制器 02 控制器 03 控制器 04 控制器 05

CI_Controller

MY_Controller

登入模組

控制器 01

Page 102: advanced introduction to codeigniter

102

直接更換核心類別

放置目錄 application/core/ 更換 input核心

application/core/input.php

class CI_Input {

public function __construct() {}

}

Page 103: advanced introduction to codeigniter

103

擴充核心類別

類別宣告必須繼承父類別

新類別名稱與檔名必須使用MY_前置字串 命名 : application/core/MY_Input.php

class MY_Input extends CI_Input {

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

Page 104: advanced introduction to codeigniter

104

自訂子類別的前置字串

編輯 application/config/config.php

$config['subclass_prefix'] = 'MY_';

Page 105: advanced introduction to codeigniter

105

作業

練習擴充 CI_Controller核心 index.php/welcome/?lang=english index.php/welcome/?lang=zh­tw

擴充核心取得 $_GET['lang']變數資料 利用此變數將 language檔案載入實現多國語系

Page 106: advanced introduction to codeigniter

106

目標

會員註冊系統

Email認証信 Form表單驗證

多國語系

會員資料編輯 個人照片上傳

會員登入

Page 107: advanced introduction to codeigniter

107

CodeIgniter核心功能不夠網站開發需求嘛 ?

Page 108: advanced introduction to codeigniter

108

歡迎使用CodeIgniter getsparks

Page 109: advanced introduction to codeigniter

109

What is Sparks?

Ruby有 RubyGemsNode.js 有 npm

CodeIgniter有 sparks

Page 110: advanced introduction to codeigniter

110

What is Sparks?

Package Management System

Making Code Easy to Find, Create, and Distribute

Page 111: advanced introduction to codeigniter

111

Get Sparks tool Now!!

一行指令就安裝完成php -r "$(curl -fsSL http://getsparks.org/go-

sparks)"

Page 112: advanced introduction to codeigniter

112

Load Sparks Library

$this->load->spark(google-url-shortener/1.0.4');$short_url = $this->google_url_api->shorten($url);

echo $url . " => " . $short_url->id . "<br />";

Page 113: advanced introduction to codeigniter

113

Installing getsparks library

http://goo.gl/lHmCX$ php tools/spark install -v1.0.4 google-url-shortener

Page 114: advanced introduction to codeigniter

114

今天課程就到這裡大家有任何問題嘛

Page 115: advanced introduction to codeigniter

115

謝謝大家對於 CodeIgniter有任何問題

可以到論壇留言http://www.codeigniter.org.tw/forum/