You are on page 1of 24

1.

Gii thiu (Phn 1)


CI l mt nn tng ng dng web (web application framework) ngun m c dng xy dng cc ng dng web ng tng tc vi PHP. N cho php cc nh pht trin xy dng mt ng dng web nhanh hn - so vi vic vit m hn tp - bng cch cung cp 1 b th vin y cho cc tc v thng thng, cng nh cung cp mt m hnh tng tc n gin v d hiu cho vic kt ni ti nhng b th vin . Phin bn chnh thc u tin ca CI c cng b vo 28 thng 2 nm 2006. Phin bn mi nht cho ti by gi l 2.0 c cng b chnh thc vo ngy 28 thng 01 nm 2011. CI khuyn khch cc lp trnh vin s dng m hnh model-view-controller architectural pattern cho cc ng dng web ca mnh. CI cng mang mt s cc khi nim c th v cc tnh nng c bn ca cc m hnh MVC khc nh Ruby on Rails: * H tr kt ni v tng tc a nn tng c s d liu. * Tng tc vi c s d liu thng qua active records. * Session Management (qun l Session). * nh dng v chun ha form v d liu u vo. * H tr Caching ton trang tng tc thc thi v gim ti ti thiu cho my ch. * Scaffolding. * H tr Template Engine hoc s dng chnh PHP tags iu hng trong Views. * H tr Hooks, cc lp ngoi (Class Extensions), v cc Plugins. Trong s cc m hnh framework MVC khc, CI c cc u im sau : * Tng thch hon ton vi PHP 4. Nu s dng PHP 5 s dng c cc tnh nng hu ch khc nh kh nng gi phng thc dy chuyn (method chaining ability). * M hnh code nh cho h thng, ci thin tc thc thi. * n gin trong vic ci t, cu hnh v cu trc th mc. * Error Logging. * Mm do trong vic nh tuyn URI (URI Routing). Framework ny tch hp thm vo mt s lp th vin khc m cc framework khc cha mc nh tch hp: * Bo mt v XSS Filtering. * Gi Email, h tr nh km, HTML/Text email, a giao thc(sendmail, SMTP, and Mail) v cc th khc. * Th vin chnh sa nh (ct nh, thay i kch thc, xoay nh, v.v..). H tr GD, ImageMagick, v NetPBM. * Upload file. * FTP Class - Tng tc vi my ch thng qua giao thc FTP. * Localization. * Phn trang t ng.

* M ha d liu - Data Encryption. * o lng tc thc thi - Benchmarking. * Application Profiling. * Lch - Calendaring Class. * User Agent Class. * Nn - Zip Encoding Class. * Trackback Class. * XML-RPC Library. * Unit Testing Class. * Search-engine Friendly URLs. * Mt lng ln cc hm h tr (helpers). S ng dng:

Trong : - index.php ng vai tr tip nhn v iu khin mi hot ng ca ng dung. - Routing nh tuyn tt c cc yu cu t HTTP cho ng dng. - Caching ch c s dng khi ng dng c s dng chc nng lu b m (cache). - Lp x l bo mt ca ng dng. - Application Controller (v cc models, libraries, helpers, plugins, ...) l cc iu khin, x l ca ng dng. - View tr v kt qu cho trnh duyt hin th. Nu ng dng c s dng chc nng cache th view coi nh c kich hot.

2. Ci t v cu hnh (Phn 2)
ci t CI, cc bn thc hin nhng bc sau: 1. Ti b framework CI ti http://codeigniter.com/download.php. 2. Gii nn gi CI bn s c 3 th mc (application, system, user_guide) v 2 file (index.php, license.txt). Trong , th mc user_guide l th mc cha ti liu hng dn s dng CI, file license.txt l file license. Ton b gi CI bn ch quan tm 2 th mc application, system v file index.php (y l ton b gi CI). 3. Copy 2 th mc application, system v file index.php vo th mc webroot ca server local (sau ny gi l localhost). Ti s dng Wampserver lm server local nn ti s copy gi CI vo

th mc www. 4. Truy cp a ch http://localhost. Nu hin ra trang welcome ca CI th bn ci t thnh cng bc u. 5. Cu hnh website vi 2 bc: * Bc 1: M file application/config/config.php cu hnh website. Trong file config.php hin ti bn ch quan tm ti $config['base_url']. y l cu hnh URL n th mc gc ca website. Nh vy, vi website ca chng ta th ti s cu hnh nh sau: M: Chn tt c
$config['base_url'] = 'http://localhost';

Kinh nghim: M: Chn tt c


$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'];

File config.php sau khi cu hnh s nh sau: M: Chn tt c


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------| Base Site URL |-------------------------------------------------------------------------| | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | If this is not set then CodeIgniter will guess the protocol, domain and | path to your installation. | */ $config['base_url'] = 'http://'.$_SERVER['HTTP_HOST']; /* |-------------------------------------------------------------------------| Index File |-------------------------------------------------------------------------| | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = 'index.php'; /* |-------------------------------------------------------------------------| URI PROTOCOL |-------------------------------------------------------------------------| | This item determines which server global should be used to retrieve the | URI string. The default setting of 'AUTO' works for most servers. | If your links do not seem to work, try one of the other delicious flavors:

| | 'AUTO' Default - auto detects | 'PATH_INFO' Uses the PATH_INFO | 'QUERY_STRING' Uses the QUERY_STRING | 'REQUEST_URI' Uses the REQUEST_URI | 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO | */ $config['uri_protocol'] = 'AUTO'; /* |-------------------------------------------------------------------------| URL suffix |-------------------------------------------------------------------------| | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------| Default Language |-------------------------------------------------------------------------| | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------| Default Character Set |-------------------------------------------------------------------------| | This determines which character set is used by default in various methods | that require a character set to be provided. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------| Enable/Disable System Hooks |-------------------------------------------------------------------------| | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE;

/* |-------------------------------------------------------------------------| Class Extension Prefix |-------------------------------------------------------------------------| | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------| Allowed URL Characters |-------------------------------------------------------------------------| | This lets you specify with a regular expression which characters are permitted | within your URLs. When someone tries to submit a URL with disallowed | characters they will get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 09~%.:_| | Leave blank to allow all characters -- but only if you are insane. | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------| Enable Query Strings |-------------------------------------------------------------------------| | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions:

| example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; // experimental not currently in use /* |-------------------------------------------------------------------------| Error Logging Threshold |-------------------------------------------------------------------------| | If you have enabled error logging, you can set an error threshold to | determine what gets logged. Threshold options are: | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------| Error Logging Directory Path |-------------------------------------------------------------------------| | Leave this BLANK unless you would like to set something other than the default | application/logs/ folder. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------| Date Format for Logs |-------------------------------------------------------------------------| | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */

$config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------| Cache Directory Path |-------------------------------------------------------------------------| | Leave this BLANK unless you would like to set something other than the default | system/cache/ folder. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------| Encryption Key |-------------------------------------------------------------------------| | If you use the Encryption class or the Session class you | MUST set an encryption key. See the user guide for info. | */ $config['encryption_key'] = ''; /* |-------------------------------------------------------------------------| Session Variables |-------------------------------------------------------------------------| | 'sess_cookie_name' = the name you want for the cookie | 'sess_expiration' = the number of SECONDS you want the session to last. | by default sessions last 7200 seconds (two hours). Set to zero for no expiration. | 'sess_expire_on_close' = Whether to cause the session to expire automatically | when the browser window is closed | 'sess_encrypt_cookie' = Whether to encrypt the cookie | 'sess_use_database' = Whether to save the session data to a database | 'sess_table_name' = The name of the session database table | 'sess_match_ip' = Whether to match the user's IP address when reading the session data | 'sess_match_useragent' = Whether to match the User Agent when reading the session data | 'sess_time_to_update' = how many seconds between CI refreshing Session Information | */ $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_expire_on_close'] = FALSE; $config['sess_encrypt_cookie'] = FALSE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE;

$config['sess_time_to_update']

= 300;

/* |-------------------------------------------------------------------------| Cookie Related Variables |-------------------------------------------------------------------------| | 'cookie_prefix' = Set a prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | */ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; /* |-------------------------------------------------------------------------| Global XSS Filtering |-------------------------------------------------------------------------| | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------| Cross Site Request Forgery |-------------------------------------------------------------------------| Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; /* |-------------------------------------------------------------------------| Output Compression |-------------------------------------------------------------------------| | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could

| even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------| Master Time Reference |-------------------------------------------------------------------------| | Options are 'local' or 'gmt'. This pref tells the system whether to use | your server's local time as the master 'now' reference, or convert it to | GMT. See the 'date helper' page of the user guide for information | regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------| Rewrite PHP Short Tags |-------------------------------------------------------------------------| | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------| Reverse Proxy IPs |-------------------------------------------------------------------------| | If your server is behind a reverse proxy, you must whitelist the proxy IP | addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR | header in order to properly identify the visitor's IP address. | Comma-delimited, e.g. '10.0.1.200,10.0.1.201' | */ $config['proxy_ips'] = ''; /* End of file config.php */ /* Location: ./application/config/config.php */

* Bc 2: M file application/config/database.php cu hnh thng s kt ni c s d liu. Hin ti, bn s quan tm ti 4 thng s sau: - $db['default']['hostname']: Tn host ca c s d liu.

- $db['default']['username']: Username kt ni ti c s d liu. - $db['default']['password']: Mt khu kt ni ti c s d liu. - $db['default']['database']: Tn c s d liu. Vi website ny ti s khai bo nh sau: M: Chn tt c
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* | ------------------------------------------------------------------| DATABASE CONNECTIVITY SETTINGS | ------------------------------------------------------------------| This file will contain the settings needed to access your database. | | For complete instructions please consult the 'Database Connection' | page of the User Guide. | | ------------------------------------------------------------------| EXPLANATION OF VARIABLES | ------------------------------------------------------------------| | ['hostname'] The hostname of your database server. | ['username'] The username used to connect to the database | ['password'] The password used to connect to the database | ['database'] The name of the database you want to connect to | ['dbdriver'] The database type. ie: mysql. Currently supported: mysql, mysqli, postgre, odbc, mssql, sqlite, oci8 | ['dbprefix'] You can add an optional prefix, which will be added | to the table name when using the Active Record class | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. | ['cache_on'] TRUE/FALSE - Enables/disables query caching | ['cachedir'] The path to the folder where cache files should be stored | ['char_set'] The character set used in communicating with the database | ['dbcollat'] The character collation used in communicating with the database | ['swap_pre'] A default table prefix that should be swapped with the dbprefix | ['autoinit'] Whether or not to automatically initialize the database. | ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections | - good for ensuring strict SQL while developing | | The $active_group variable lets you choose which connection group to | make active. By default there is only one group (the 'default' group). | | The $active_record variables lets you determine whether or not to load | the active record class */ $active_group = 'default'; $active_record = TRUE; $db['default']['hostname'] $db['default']['username'] $db['default']['password'] $db['default']['database'] = = = = 'localhost'; 'root'; ''; 'project_ci';

$db['default']['dbdriver'] $db['default']['dbprefix'] $db['default']['pconnect'] $db['default']['db_debug'] $db['default']['cache_on'] $db['default']['cachedir'] $db['default']['char_set'] $db['default']['dbcollat'] $db['default']['swap_pre'] $db['default']['autoinit'] $db['default']['stricton']

= = = = = = = = = = =

'mysql'; ''; TRUE; TRUE; FALSE; ''; 'utf8'; 'utf8_general_ci'; ''; TRUE; FALSE;

/* End of file database.php */ /* Location: ./application/config/database.php */

Vi cc bc trn, bn ci t v cu hnh c bn cho website s dng CI. Cc cu hnh khc bn c th tm hiu thm hoc reply li ti topic qui nh.

3. URLs (Phn 3)
Trong phn ny chng ta s tm hiu v cch CI x l URL gi cc controller, method. Mc nh, URL ca CI c thit k thn thin vi cc my tm kim, ti u SEO bng cch s dng cc phn khc (gi l segment) thay v s dng URL kiu truyn thng (query string). Bn c th xem 1 v d v cch m CI thit k URL: example.com/news/article/my_article Tuy nhin, kiu URL truyn thng (query string) cc bn cng c th s dng bng cch cu hnh trong file application/config/config.php nh sau: M: Chn tt c
$config['enable_query_strings'] = TRUE;

By gi ta s phn tch URL sau: example.com/index.php/class/function/ID Vi URL trn, ta c 3 segment l class, function v ID. Trong : - Segment class s c CI gi ti controller tn class (class cng chnh l 1 lp). - Segment function c CI gi ti phng thc tn function ca lp class trn. - Segment ID c CI hiu nh l 1 bin ca phng thc function (Bn cng c th truyn vo nhiu bin). lm vic vi cc segment ca URL, CI xy dng sn cc helper gip bn lm vic vi cc URI segment 1 cch d dng, v vy bn yn tm v cch thit k URL ny ca CI.

Vi URL trn, chng ta thy s xut hin ca index.php, bn cng c th b index.php bng cch s dng .htaccess (ch hot ng trn server Linux). Code .htaccess loi b index.php nh sau: M: Chn tt c
RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Nh vy, sau khi s dng .htaccess ta s c URL thn thin sau: example.com/class/function/ID Thm phn m rng cho URL: Bn thng thy mt s website c ng URL nh sau: codeigniter.com/user_guide/general/urls.html (Phn ui .html). CI cng c th lm c nh vy ch vi 1 cu hnh n gin trong file application/config/config.php: M: Chn tt c
$config['url_suffix'] = '.html';

lc URL ca chng ta s l: example.com/class/function/ID.html Kch hot query string: Trong trng hp bn mun s dng kiu URL truyn thng (query string), bn c th tin hnh cu hnh kch hot trong file application/config/config.php: M: Chn tt c
$config['enable_query_strings'] = TRUE; $config['controller_trigger'] = 'c';//Bin ly tn controller $config['function_trigger'] = 'm';//Bin ly tn phng thc

Lc , URL ca chng ta s tr thnh: example.com/index.php?c=class&m=function&id=ID

4. Controllers (Phn 4)
Controller c th c xem nh tri tim ca ton b ng dng. N iu khin cc yu cu HTTP t ngi dng. Tt c mi x l do ngi dng tung tc u c x l ti controller, controller

s lm nhim v giao tip gia cc yu cu ngi dng (hay chnh xc hn l cc yu cu HTTP) vi ng dng cng nh vi c s d liu. Controller l 1 file class m n c t tn sao cho c mi lin h vi URI. V d vi URL sau: example.com/blog Vi URL th CI s tm v gi controller blog.php v ta c th tm thy controller ny trong th mc application/controllers/blog.php. Chng ta s bt u vi ng dng u tin "HELLO WORD!": Chng ta s to 1 controller c tn l blog (blog.php) v save trong th mc application/controllers/ vi ni dung nh sau: M: Chn tt c
<?php class Blog extends CI_Controller { function __construct() { parent::__construct(); } function index() { echo 'Hello World!'; } } ?>

Vi controller c to trn, bn s gi controller ny vi URL nh sau: example.com/blog Lc , kt qu m chng ta thy s l cu "Hello World!". Cc bn ch v cch to 1 controller: - File controller phi c t tn trng vi tn controller (tn class) nhng lun lun l ch thng v c t trong th mc application/controllers/ (hoc th mc con trong application/controllers/). - Tn controller (chnh xc hn l tn ca class) phi c vit hoa ch ci u tin nh v d m bn thy (Blog) v controller phi c extends class CI_Controller. - Mi controller lun lun c phng thc khi to __construct() vi cu lnh bn trong nh bn thy v d trn: M: Chn tt c
function __construct() { parent::__construct(); }

Bn thy vi controller blog trn, ta ch cn truy cp URL example.com/blog l CI s t ng tm n controller blog th thi. Vy ti sao CI hiu l s gi ti phng thc index()?. Tr li: Bi v vi URL trn th CI hiu ngm rng bn ang truy cp ti controller blog v ang gi phng thc index() (C th xem phng thc index() l phng thc m CI s t ng hiu nu ta khng truyn tn phng thc vo URL). Chng ta s xt tip 1 v d khc nh sau: M: Chn tt c
<?php class Blog extends CI_Controller { function __construct() { parent::__construct(); } function index() { echo 'Hello World!'; } function comments() { echo 'Look at this!'; } } ?>

Vi v d trn, nu bn mun truy cp ti phng thc comments() in ra cu "Look at this!" th bn s truy cp URL sau: example.com/blog/comments Vi URL trn, CI s t ng tm n controller blog v gi phng thc comments() in ra cu "Look at this!". Tip tc xt 1 v d khc, v d ln ny ta s truyn vo phng thc comments() bin $id, tc lc ny phng thc s tr thnh comments($id): M: Chn tt c
<?php class Blog extends CI_Controller { function __construct() { parent::__construct(); } function index() { echo 'Hello World!'; } function comments($id)

{ echo 'Look at this! ID comment is '.$id; } } ?>

Vi v d trn, bn truy cp URL sau: example.com/blog/comments/12 Lc ny, kt qu bn s thy l: Trch dn: Look at this! ID comment is 12 Theo mc nh, CI s x l URL v gi cc controller (cng nh phng thc tng ng) nh ta thy trn. Ngoi ra, CI cn cung cp cho chng ta 1 "cng c" gip cho chng ta hon ton ty bin vic thit k URL, l routes. V routes ti s hng dn trong 1 phn khc c cp sau. Vi nhng g ti cung cp v controller c trnh by trn ch mang tnh c bn, cc bn c th tm hiu thm v controller ti http://codeigniter.com/user_guide/gener ... llers.html.

5. Views (Phn 5)
View l 1 trang web hay 1 phn ca trang web nh header, footer, sidebar... Bn hiu n gin, view ch l nhng file HTML nh hnh trang web (phn ln u c chn code PHP ly d liu ng). Thng thng, ton b nhng g bn thy trn trnh duyt th c xem nh l 1 view. V c bn, view khng th c gi trc tip m n lun c gi thng qua 1 controller theo ng m hnh MVC m ta thng bit ti. To 1 view: Bn to 1 file view cho controller blog phn 4 vi ni dung nh sau: M: Chn tt c
<html> <head> <title>My Blog</title> </head> <body> Welcome to my Blog! </body> </html>

Tt c file view ca ng dng s c lu tr trong th mc application/views. Nh vy vi file view ca chng ta trn, ti s lu vi tn l blogview.php trong th mc application/views. Vi view trn ch n thun l 1 trang HTML n gin. Gi 1 view t controller: gi view, bn s dng c php lnh: M: Chn tt c
$this->load->view('view_name');

Vi view_name l tn file view bn mun load nhng khng km theo phn m rng (.php). Nh vy, vi file blogview.php to trn chng ta s c c php gi file blogview.php nh sau: M: Chn tt c
$this->load->view('blogview');

V ta s c controller blog vi ni dung lnh nh sau: M: Chn tt c


<?php class Blog extends CI_Controller { function __construct() { parent::__construct(); } function index() { //Load view $this->load->view('blogview'); } } ?>

Khi bn truy cp URL sau: example.com/blog Kt qu s l: Trch dn: Welcome to my Blog! Bn cng c th load nhiu view trong 1 controller nh v d sau: M: Chn tt c
<?php class Blog extends CI_Controller { function __construct() { parent::__construct(); }

function index() { //Load view $this->load->view('header'); $this->load->view('menu'); $this->load->view('blogview'); $this->load->view('footer'); } } ?>

Trng hp bn to view bn trong 1 th mc con ca th mc application/views (v d ti t file blogview.php trong th mc application/views/subfolder) bn c th s dng c php lnh sau gi view: M: Chn tt c
$this->load->view('subfolder/blogview');

Truyn d liu t controller ra view: Ton b qu trnh x l tng tc d liu u c thc hin controller (tr vic ly d liu t database l thc hin model s ni sau) nn kt qu tr v s nm trong controller. Vy lm cch no truyn d liu ny ra ngoi view ta c th trnh by theo mun? Vi CI th cng vic ny rt n gin: Bn ch vic gn ton b cc d liu mun truyn ra view vo 1 mng v truyn vo tham s th 2 ca phng thc load view nh v d di y: M: Chn tt c
$data = array( 'title' => 'My Title', 'heading' => 'My Heading', 'message' => 'My Message' ); $this->load->view('blogview', $data);

Vi v d trn, khi ra ngoi blogview bn s c cc bin $title, $heading v $message s dng. Chng ta xt v d hon chnh sau: To controller blog (application/controllers/blog.php) vi ni dung sau: M: Chn tt c
<?php class Blog extends CI_Controller { function __construct() { parent::__construct(); } function index() { $data['title'] = 'Tiu website'; $data['messagge'] = 'Hello word!';

//Load view $this->load->view('blogview', $data); } } ?>

To view blogview (application/views/blogview.php) vi ni dung sau: M: Chn tt c


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

Bn truy cp URL: example.com/blog Chng ta s c kt qu: Trch dn: Hello word! (Lu : Chui "Tiu " th xut hin trn thanh tiu ca trnh duyt). Khi d liu c truyn t controller ra view s vn gi nguyn kiu d liu. V d kiu d trong controller l chui (string) th ngoi view cng s l chui. Tng t, kiu mng (array), kiu i tng (object)... khi truyn ra view vn gi nguyn kiu d liu.

6. Models (Phn 6)
Model l 1 lp PHP c thit k tng tc vi c s d liu ca bn. Chng hn nh bn vit 1 trang blog s dng CI th thng bn s c cc thao tc vi c s d liu nh select, thm, xa, sa... V tt nhin, vai tr ca model l thc hin nhng cng vic ny. Chng ta xt 1 v d di y: M: Chn tt c
class Blogmodel extends CI_Model { var $title = ''; var $content = ''; var $date = ''; function __construct() { // Call the Model constructor parent::__construct();

} function get_last_ten_entries() { $query = $this->db->get('entries', 10); return $query->result(); } function insert_entry() { $this->title = $_POST['title']; // please read the below note $this->content = $_POST['content']; $this->date = time(); $this->db->insert('entries', $this); } function update_entry() { $this->title = $_POST['title']; $this->content = $_POST['content']; $this->date = time(); $this->db->update('entries', $this, array('id' => $_POST['id'])); } }

Vi v d trn, model Blogmodel nh ngha ra cc phng thc nh get_last_ten_entries(), insert_entry() hay update_entry(). Tt c cc phng thc ny u tng tc vi c s d liu ly d liu ln hay thm mi, chnh sa d liu. Mt model (hay cn gi class model) c to v t trong th mc application/models. V 1 iu lu , tn file phi trng vi tn ca class model nhng vit thng (ging vi controller). Vi v d trn th ta s c file application/models/blogmodel.php. Ngoi ra 1 class model lun lun extends CI_Model. Mt class model c ni dung tng t nh sau: M: Chn tt c
class Model_name extends CI_Model { function __construct() { parent::__construct(); } }

s dng 1 model, trc tin bn phi load model . V d s dng blogmodel trn, bn s phi load blogmodel trc khi s dng cc phng thc nh get_last_ten_entries(), insert_entry() hay update_entry() vi c php sau: M: Chn tt c
$this->load->model('blogmodel');

Chng ta xt li controller blog phn 5, cc bn mun s dng blogmodel cho controller blog th controller blog s c ni dung nh sau:

M: Chn tt c
class Blog extends CI_Controller { function __construct() { parent::__construct(); } function index() { $this->load->model('Blogmodel'); $data['query'] = $this->Blogmodel->get_last_ten_entries(); $this->load->view('blog', $data); } }

Trong v dn trn, ngoi c php load blogmodel th bn cn cn phi ch ti cu lnh sau: M: Chn tt c
$data['query'] = $this->Blogmodel->get_last_ten_entries();

y l cu lnh gi ti phng thc get_last_ten_entries() v gn cho $data['query']. Nh vy gi ti cc phng thc c nh ngha trong 1 model, CI thit k 1 cch gi nh sau: M: Chn tt c
$this->model_name->method();

Bn ch : model_name l tn ca model v phi vit thng v method() l 1 phng thc trong class model. y cng l cch s dng chung cho cc th vin ca CI. lm vic vi model, cc bn cn phi tm hiu thm v th vin Database m ti s cp sau. Th vin Database nh ngha sn cc phng thc tng tc an ton vi c s d liu v c l y l mt th vin cha nhiu phng thc nht ca CI.

7. Helper Functions (Phn 7)


Nhng phn trc cc bn lm quen vi CI, ch vi nhng phn trn bn c th vit ng dng web ca mnh bng CI ri. phn ny, ti s gii thiu v cc hm (function) tr gip (gi l helper) gip cho cng vic vit code ca bn tr nn n gin hn rt nhiu. Helper l cch gi dnh cho cc function c CI (hoc k c ngi dng) nh ngha sn s dng trong ng dng ca mnh 1 cch nhanh chng. CI cung cp sn rt nhiu helper gip bn lm vic vi CI nhanh chng hn nhiu, 1 vi helper c CI nh ngha v theo ti n c s dng thng xuyn nht l: url, form, language, captcha, email ... Vic s dng 1 helper rt n gin, trc tin bn phi load helper cn s dng bng c php sau: M: Chn tt c

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

V d bn mun load helper url trong controller blog, bn s c on code nh sau: M: Chn tt c
<?php class Blog extends CI_Controller { function __construct() { parent::__construct(); } function index() { $this->load->helper('url');//Load helper url echo base_url();//S dng 1 hm trong helper url } } ?>

Nh v d trn, helper url c load bi cu lnh $this->load->helper('url'); v hm base_url() trong helper url c s dng vi li gi hm bnh thng m chng ta vn bit trong PHP. Chng ta cng c th load 1 lc nhiu helper bng c php lnh nh sau: M: Chn tt c
$this->load->helper( array('helper1', 'helper2', 'helper3') );

V d, bn mun load cc helper url, form, language bn s c c php nh sau: M: Chn tt c


$this->load->helper( array('url', 'form', 'language') );

Vic s dng cc hm c nh ngha sn trong helper nh ti ni trn l chng ta s gi hm bnh thng nh trong PHP. Ngoi nhng helper do CI nh ngha sn (v c lu trong th mc system/helpers) th chng ta cng c th t to ra cc helper vi qui tc nh sau: 1. Tn file helper phi l ch thng v c subfix (phn ui) l _helper. V d ti mun to 1 helper c tn l blog th ti s to 1 file c tn l blog_helper.php v c lu trong th mc application/helpers hoc lu vo th mc system/helpers cng c (nhng ti khuyn bn khng nn can thip vo th mc system ca CI). 2. Tt c cc hm bn nh ngha trong helper ca bn (v d y l helper blog) phi l duy nht (khng c trng vi cc hm ca cc helper khc).

8. Libraries (Phn 8)
Library l th vin c CI to ra nhm to ra cc class chc nng gip cho bn lm vic nhanh chng vi ng dng. C th xem library c vai tr ging vi helper.

Mi library l 1 class c nh ngha sn cc phng thc tin ch. Tt c cc library do CI nh ngha c t trong th mc system/libraies. Ngoi ra, chng ta cng c th t nh ngha 1 library ring ca chnh mnh. Nhng library do chng ta nh ngha, c th c lu trong th mc system/libraries nhng ti khuyn bn nn t trong th mc application/libraries. Vic s dng 1 library tng t nh s dng helper vi c php nh sau: M: Chn tt c
$this->load->library('class_name');

V d, CI nh ngha sn library upload, by gi chng ta mun s dng library upload trong controller blog th controller blog s c ni dung sau: M: Chn tt c
<?php class Blog extends CI_Controller { function __construct() { parent::__construct(); } function index() { $this->load->library('upload');//Load library upload } } ?>

Tuy nhin, s dng cc phng thc ca cc library ny i hi bn phi tm hiu v library . Docs v cc libary c CI trnh by kh r rng, cc bn c th tham kho ti http://codeigniter.com/user_guide. V chi tit cch s dng cc library ti s hng dn nhng phn sau. Chng ta cng c th load 1 lc nhiu library (ging nh helper) vi c php nh sau: M: Chn tt c
$this->load->library(array('class_name_1', 'class_name_2'));

V d, ti mun load 2 library upload v cart th ti s c c php nh sau: M: Chn tt c


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

Vn to 1 library cho ring bn, bn cn tun theo cc qui tc sau: 1. Tn file phi trng vi tn ca class v phi l ch thng. V d ti mun to ra library payment th ti s to 1 file c tn l payment.php v lu vo th mc application/libraries (hoc th mc system/libraries). File payment.php s cha class c tn l Payment (lu ch ci u tin ca class lun l ch hoa). 2. Tn ca library l duy nht (khng trng vi cc library khc).

9. URI Routing (Phn 9)


Thng thng th CI to ra 1 mi quan h 1 - 1 gia URI vi cc controller (class) v cc phng thc (method) theo kiu class/method. Cch phn on ca CI c th biu din bi v d sau: example.com/class/function/id Vi v d trn th chng ta ang gi ti controller (hay cn gi class) tn l class vi phng thc c gi l function v bin id ca function. y l cch gi mc nh ca CI. Chng ta cng bit, CI cung cp nhiu tin ch gip cho chng ta c th t do ty bin ng dng ca mnh v trng hp ny CI cng cung cp 1 chc nng l routing (nh tuyn) gip cho chng ta c th iu khin URI 1 cch d dng m khng nht thit phi theo khung mu nh v d trn. V d, nu chng ta c controller blog v function l index() th URL m chng ta truy cp s phi l: example.com/blog/index Nhng by gi ti mun i URL trn thnh: example.com/ca-nhan/tai-khoan Vi URL mi ny ti cng truy cp vo controller blog v gi phng thc index() th sao? Tt nhin, chng ta c th lm iu vi routing. Vi v d trn th chng ta s c routing nh sau: M: Chn tt c
$route['ca-nhan/tai-khoan'] = "blog/index";

thit k routing ny, CI cung cp 1 file application/config/routes.php. Bn ch vic m file ny ln v thm vo mu routing trn. Ni dung file routes.php mc nh bn ch cn quan tm ti 2 dng lnh sau: M: Chn tt c
$route['default_controller'] = "welcome"; $route['404_override'] = '';

Dng lnh $route['default_controller'] = "welcome"; l dng lnh nh ngha controller mc nh khi truy cp website. y, mc nh l controller welcome s c gi vi phng thc l index() (Nu l phng thc index() c gi th chng ta c th khng cn thit khai bo). Dng lnh $route['404_override'] = ''; l dng lnh gi ti trang li 404. Nu rng th CI s gi ti trang 404 mc nh. Nh vy, vi v d trn th file application/config/routes.php ca chng ta s c ni dung nh sau:

M: Chn tt c
$route['default_controller'] = "welcome"; $route['404_override'] = ''; $route['ca-nhan/tai-khoan'] = "blog/index";

Hoc M: Chn tt c
$route['default_controller'] = "welcome"; $route['404_override'] = ''; $route['ca-nhan/tai-khoan'] = "blog";

Hai ni dung trn khc nhau dng lnh th 3 (cc bn c gng tm xem s khc bit nha ). Nh vy, vi controller blog v file routes.php trn th chng ta c th truy cp controller blog bng 1 trong 2 cch sau: example.com/blog/index Hoc example.com/ca-nhan/tai-khoan Routing ca CI cho php bn s dng cc Regular Expressions ca PHP. Ngoi ra, CI cng cung cp 2 Regular Expressions mc nh l: :num Ch chp nhn s. :any Chp nhn tt c cc k t.

You might also like