advanced introduction to codeigniter
TRANSCRIPT
Outline
如何善用使用 CodeIgniter內建函式庫 移植及撰寫個人 Library 擴充核心程式碼
GetSparks簡介
3
如何善用 CodeIgniter函式庫 ?
4
Loader Library系統自動初始化
5
$this->load->library('class', $config, 'object')
$this->load->library('email');
$this->email->some_function().
如何使用
6
同時載入多個函式庫
$this->load->library(array('email', 'table'));
7
傳入參數
$this->load->library('class', $config)
example: $this->load->library('email')
$config = array ( 'mailtype' => 'html', 'charset' => 'utf-8, 'priority' => '1');
8
public function __construct($config = array()){ if (count($config) > 0) { $this->initialize($config); }}
Library參數初始化
initialize為 class其中一個 function
9
指定物件名稱
$this->load->library('session', $config)$this->session->some_function()
$this->load->library('session', $config, 'my_sess')$this->my_sess->some_function()
10
Config Library系統自動初始化
11
系統自動讀取網站設定檔
(application/config/config.php)
12
將固定資料都存放在 config目錄
application/config/bitly.php
13
範例存放 API Key
<?php$config['user_name'] = 'appleboy';$config['api_key'] = 'xxxxxxxx';$config['format'] = 'json';?>
14
取得設定檔資料
$this->config->load('bitly');$this->config->item('api_key');
15
在這裡大家有沒有一個疑問假設載入兩個設定檔
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';?>
17
$this->config->load('bitly');$this->config->load('tiny');
18
輸出資料會是 ?
$this->config->item('api_key');
答案 : api_key_02
19
為什麼資料變數會衝突呢 ?那該如何解決 ?
20
系統載入流程
檢查 application/config/目錄檔案是否存在 不存在 (continue) 存在 (include方式載入 )
後載入覆蓋前面設定檔
21
解決變數衝突
第二個參數設定為 true
$this->config->load('bitly', true);$this->config->load('tiny', true);
22
衝突讀取方式
加入第三參數
$this->config->item('api_key', 'bitly');$this->config->item('api_key', 'tiny');
23
另類解決方式
item key為什麼會出現衝突 ?item key為什麼會出現衝突 ?
24
Web程式設計師對變數命名方式大不同
(資料庫欄位命名 )user_nameUserNameusername
25
改變 key命名方式prefix_name + item_name
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';?>
27
此命名方式可以加速其他程式設計師閱讀程式碼方便性
28
作業一
新增 template設定檔 base_title site_keyword site_description
將設定檔內容讀出並載入到 layout
29
Email Library大量寄信
30
Email Class
多重收件人
副本 (CC)和密件副本 (BCCs) 支援 HTML或者是純文字 (Plaintext)郵件 附件檔案
Email Debugging tools
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();
32
$this>email>to() $this>email>cc() $this>email>bcc()
可以帶入陣列或單一資料
$this>email>send()
if ( ! $this->email->send()){ echo $this->email->print_debugger();}
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();
34
File Uploading Library(多檔案上傳 )
35
檔案上傳流程
設定存放上傳目錄權限
調整 php.ini檔案上傳設定 建立上傳表單
驗證使用者上傳檔案
印出檔案訊息並且寫到資料庫
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);}
37
設定參數
upload_path(絕對或者是相對即可 ) allowed_types(可上傳類型用豎線 '|'分開 ) overwrite(相同檔名則覆蓋 ) max_size(檔案大小限制 ) max_width(圖片專用 ) max_height(圖片專用 ) encrypt_name(檔名加密字串取代 )
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"
39
作業二
新增上傳表單 將上傳檔案資訊存入資料庫
並且將檔案以附件寄給該使用者
40
Form Validation Library表單驗證
41
欄位驗證
1. 欄位包含非法字元2. 欄位長度必須大於 minimum 3. 欄位長度必須小於 maximum4. 使用者名稱不能重複 (資料庫比對 )
42
Controller
$this->load->library('form_validation');
if ($this->form_validation->run() == false){ $this->load->view('myform');}else{ $this->load->view('formsuccess');}
43
表單驗證規則
$this->form_validation->set_rules()
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');
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');}
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]');
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) 皆可處理
48
記憶表單
欄位驗證失敗回到表單
顯示之前留下的資料
$this->load->helper('form')
set_value('username', 'appleboy')set_select('myselect', 'one', true)set_checkbox('mycheck[]', '1', true)set_radio('myradio', '1', true)
49
自行設計驗證函數
$this->form_validation->set_rules('username', '帳號 ', 'callback_username_check')
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'); }}
51
Call back function
public function username_check($str){ if ($str == 'test') { return FALSE; } else { return TRUE; }}
52
定義錯誤訊息
$this->form_validation->set_message('rule', 'error message')
53
錯誤訊息
全部顯示
<?php echo validation_errors(); ?>個別顯示
<?php echo form_error('file_name'); ?>
54
作業三
使用者註冊表單 欄位 :Email,密碼 ,確認密碼 撰寫 call back function確認帳號是否存在 自訂錯誤訊息
55
Image Manipulation Library(影像處理 )
56
影像處理 (GD vs ImageMagic)
修改尺寸
建立縮圖
圖片裁剪
圖片旋轉
浮水印
57
個人建議大量圖形網站用ImageMagic
(支援 command line 執行 )(獨立處理圖片 )
(不需要動到前端 Server)
58
如果公司經費許可
AWS S3雲端儲存服務Simple Storage Service
59
$this->load->library('image_lib')
初始化
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();
61
參數設定
image_library: GD, GD2, ImageMagick, NetPBM library_path: Linux, Windows底下路徑 source_image: 絕對 /相對路徑 new_image: 輸出檔案絕對 /相對路徑 width:圖片寬度 height:圖片高度 create_thumb:避免覆蓋原檔案
62
錯誤訊息
if ( ! $this->image_lib->resize()){ echo $this->image_lib->display_errors();}
63
影像處理函數
$this>image_lib>resize() $this>image_lib>crop() $this>image_lib>rotate() $this>image_lib>clear()
64
影像處理函數
$this>image_lib>resize() $this>image_lib>crop() $this>image_lib>rotate() $this>image_lib>clear()
65
務必設定
$config['create_thumb'] = true; $config['new_image'] = '/path/new_image.jpg';
避免原始檔案被處理 (保留原檔 )
66
影像處理函數
$this>image_lib>resize() $this>image_lib>crop() $this>image_lib>rotate() $this>image_lib>clear()
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();}
68
影像處理函數
$this>image_lib>resize() $this>image_lib>crop() $this>image_lib>rotate() $this>image_lib>clear()
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();}
70
rotation_angle參數
90(順時針 90度 ) 180(順時針 180度 ) 270(順時針 270度 ) hor(水平旋轉 ) vrt(垂直旋轉 )
71
影像處理函數
$this>image_lib>resize() $this>image_lib>crop() $this>image_lib>rotate() $this>image_lib>clear()
72
$this->image_lib->clear()重置所有設定項目
73
作業
增加使用者頭像上傳
限制上傳檔案型態 (jpeg,jpg,png,gif) 可以自訂圖像 (隨時更改 ) 製作縮圖顯示於使用者列表
74
Language Library(多國語系 )
75
兩個存放語系目錄
application/language/[english|zhtw] system/language/[english|zhtw] 先後讀取
application/config/config.php 設定預設語系
76
建立語言檔案
檔案命名方式
error_lang.php
內容以 $lang陣列方式表示 $lang['language_key'] = "我是中文 ";
77
$lang['error_email'] = "您必須填入電子郵件 ";$lang['error_url'] = "您必須填入完整網址 ";$lang['error_username'] = "您必須填入帳號名稱 ";
避免衝突
78
讀取語言檔案
$this->lang->load('filename', 'language')
79
讀取資料
Language helper函式
lang('language_key')
$this->load->helper('language');
80
作業
請用下列 URL切換中英文語系 index.php/controller/function?lang=zhtw
81
Pagination Library(分頁處理 )
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();
83
分頁參數
base_url:完整的 URL路徑 ,包含了控制器(controller)/函數 (function)
total_rows:總筆數 per_page:單頁顯示幾筆 uri_segment: URI哪個部份包含了頁數 num_links:您目前所在頁數前面跟後面所顯示的分頁數量
use_page_numbers:用 page number顯示
84
講了這麼多 CodeIgniter內建 Library那該如何撰寫屬於自己的套件呢
85
如果別人寫好的 Library該如何無痛導入到
CodeIgniter
86
注意事項
檔案命名
一律採用小寫命名 , 如 my_class.php
類別宣告
類別宣告第一個字母必須為大寫 ,如 class My_class
87
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function some_function() { }}
/* End of file Someclass.php */
88
初始化類別傳遞參數
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('someclass', $params);
89
public function __construct($config = array()){ If ( ! empty($config)) { $this->initialize($config); }}
90
在 Library裡該如何使用CodeIgniter其他資源呢 ?
91
$this->load->helper('url');$this->load->library('session');$this->config->item('base_url');
92
$this->_obj =& get_instance();
93
public function __construct(){ $this->_obj =& get_instance(); $this->_obj->load->config('google_url_api');}
94
作業
建立個人專用 Library 將 goo.gl php library導入
http://code.google.com/p/googlphp/
95
網站一定會有共同處理的地方(多國語系 )
(多重登入 Facebook,Google)
96
如果有 10個 Controller那不就 10個檔案都加上相同程式碼?
97
這時候就需要
擴充核心函式庫
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都需要有共同的變數及函數
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
更改變數及函數則大家一起變動
100
控制器 01
登入函式 登入函式 登入函式 登入函式登入函式
控制器 02 控制器 03 控制器 04 控制器 05
CI_Controller
101
控制器 02 控制器 03 控制器 04 控制器 05
CI_Controller
MY_Controller
登入模組
控制器 01
102
直接更換核心類別
放置目錄 application/core/ 更換 input核心
application/core/input.php
class CI_Input {
public function __construct() {}
}
103
擴充核心類別
類別宣告必須繼承父類別
新類別名稱與檔名必須使用MY_前置字串 命名 : application/core/MY_Input.php
class MY_Input extends CI_Input {
function __construct() { parent::__construct(); }}
104
自訂子類別的前置字串
編輯 application/config/config.php
$config['subclass_prefix'] = 'MY_';
105
作業
練習擴充 CI_Controller核心 index.php/welcome/?lang=english index.php/welcome/?lang=zhtw
擴充核心取得 $_GET['lang']變數資料 利用此變數將 language檔案載入實現多國語系
106
目標
會員註冊系統
Email認証信 Form表單驗證
多國語系
會員資料編輯 個人照片上傳
會員登入
107
CodeIgniter核心功能不夠網站開發需求嘛 ?
108
歡迎使用CodeIgniter getsparks
109
What is Sparks?
Ruby有 RubyGemsNode.js 有 npm
CodeIgniter有 sparks
110
What is Sparks?
Package Management System
Making Code Easy to Find, Create, and Distribute
111
Get Sparks tool Now!!
一行指令就安裝完成php -r "$(curl -fsSL http://getsparks.org/go-
sparks)"
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 />";
113
Installing getsparks library
http://goo.gl/lHmCX$ php tools/spark install -v1.0.4 google-url-shortener
114
今天課程就到這裡大家有任何問題嘛
115
謝謝大家對於 CodeIgniter有任何問題
可以到論壇留言http://www.codeigniter.org.tw/forum/