Bài Này Sẽ Cung CấP Cho Các BạN MớI Làm Quen Codeigniter NhữNg Thông Tin Cơ BảN NhấT Mà BạN CầN Để Có Thể Code Web Trong Vòng Chỉ 40 Phút Thôi. Bài ViếT Sẽ HướNg DẫN TừNg BướC Từ Cài ĐặT, Sử DụNg Model Để Thao Tác VớI Database, Viêt Logic Và CuốI Cùng Là HiểN Thị Ra Màn Hình. Chúc Các BạN Tìm ĐượC Cho Mình MộT Framework Phù HợP Để BắT ĐầU.

Bài viết này sẽ không đề cập sâu đến lợi ích của việc sử dụng Framwork MVC các bạn sẽ tự tìm hiểu MVC là gì và vì sao chúng ta nên sử dụng mô hình MVC trong các bài khác.

CODEIGNITER là gì?

Codeigniter là một PHP MVC framework với cấu trúc code khá dễ hiểu, dễ dàng debug, dễ dàng mở rộng và phát triển với 1 team nhiều người cùng tham gia. Chính website Http://danlaptrinh.com cũng được xây dựng bằng Codeigniter.

Nếu bạn so sánh codeigniter với một framework như Zend, Codeigniter không bắt buộc người code phải sử dụng mô mình cấu trúc MVC. Đó có thể xem là nhược điểm hoặc ưu điểm tùy thuộc vào việc bạn muốn gì ở Codeigniter và bạn sử dụng nó như thế nào.

Hiện tại có rất nhiều php framework mà bạn có thể tìm hiểu để chọn ra cái nào là tốt nhất và phù hợp với chính bạn. Dưới dây là một số lý do chính khiến cho Tôi và team của tôi chọn Codeigniter là framework dùng để phát triển và gắn bó.

  • Codeigniter rất nhẹ – So sánh với các PHP frameworks khác thì CodeIgniter rất là nhẹ, điều đó có nghĩa là bạn có thể tạo ra một website có tốc độ và thời gian đáp ứng nhanh.
  • Không yêu cầu cài đặt – Không giống như các PHP frameworks khác Codeigniter không yêu cầu cài đặt, bạn chỉ việc down về, vứt vào trong thư mục web và chạy. Không tin cứ thử xem.
  • Cộng động rộng – CodeIgniter có một công đồng khá lớn và hoạt động rất tích cực. Điều đó có nghĩa là có rất nhiều người biết, và sẵn sàng chia sẻ với bạn, giúp đỡ bạn khi bạn gặp phải vấn đề gì khoai. Thực tế là tôi làm 4 năm với Codeigniter và chưa gặp vấn đề nào mà cộng đồng không có câu trả lời cả.
  • Tài liệu viết cực tốt, vô cùng dễ hiểu – CodeIgniter documents thực sự dễ hiểu với ví dụ đơn giản đi kèm. Tin tôi đi.
  • Linh hoạt – CodeIgniter cho phép bạn kế thừa hay mở rộng kiến trúc cơ bản của nó, làm nó dễ dàng hơn, tăng năng suất và bạn có thể làm mọi thứ mình muốn, theo ý mình một cách không giới hạn. Thông thường chúng tôi thường xây dựng 1 model, controller riêng cho mình kế thừa từ class cơ bản và sử dụng nó thay vì class gốc của Codeigniter.

Bây giờ thì bạn đã biết tại sao tôi sử dụng Codeigniter, hãy bắt đầu với Tutorial này nhé, sau đó thì bạn có thể tìm hiểu thêm tất cả những lợi ích của nó đang chờ bạn khám phá.

CODEIGNITER Start!!

Như đã giới thiệu, codeigniter không yêu cầu cài đặt, chúng ta chỉ việc lấy phiên bản mới nhất và copy vào cấu trúc thư mục của mình. Sau đó thì có thể chạy luôn hoặc thay đổi một số config nhỏ để phù hợp với yêu cầu của chúng ta.

DOWNLOAD CODEIGNITER

Để bắt đầu codeigniter tutorial, vào trang http://ellislab.com/codeigniter và download version mới nhất. Tất cả chỉ có thế.

TạO CấU Trúc Thư MụC Cho CODEIGNITER

Sau khi download, giải nén vào thư mục bất kỳ. Bạn sẽ thấy thư mục như hình dưới:

Download Codeigniter

Bây giờ chúng ta cần đưa các file này vào thư mục web của chúng ta. Thông thường thư mục web của chúng ta sẽ có thư mục là thư mục gốc “public_html” hoặc “www”. Bạn tạo thư mục “codeigniter” như hình dưới:

Codeigniter Project

Bây giờ chúng ta copy thư mục system application vào thư mục codeigniter nhé (user_guilde là hướng dẫncodeigniter có thể bỏ đi hoặc lưu lại chỗ nào đó để tham khảo khi cần):

Codeigniter System Folder

Sau khi copy ta có cấu trúc thư mục như sau, okie có vấn đề gì không nào?

Codeigniter Directory Structure

Thay ĐổI Chút CấU Hình Codeigniter

Bây giờ chúng ta đã copy các file cần thiết vào chỗ của nó, bây giờ chúng ta cần là cấu hình để codeigniter biết tìm các file đó ở đâu. Trong thư mục các bạn giải nén ban đầu có 1 file index.php:

Codeigniter Index File

Copy file này vào thư mục web gốc nhé (public_html, www) hãy mở file này bằng editer nào bạn muốn và tìm đoạn $system_path = 'system':


/*
 *---------------------------------------------------------------
 * SYSTEM FOLDER NAME
 *---------------------------------------------------------------
 *
 * This variable must contain the name of your "system" folder.
 * Include the path if the folder is not in the same  directory
 * as this file.
 *
 */
 $system_path = 'system';

/*
 *---------------------------------------------------------------
 * APPLICATION FOLDER NAME
 *---------------------------------------------------------------
 *
 * If you want this front controller to use a different "application"
 * folder then the default one you can set its name here. The folder
 * can also be renamed or relocated anywhere on your server.  If
 * you do, use a full server path. For more info please see the user guide:
 * http://codeigniter.com/user_guide/general/managing_apps.html
 *
 * NO TRAILING SLASH!
 *
 */
 $application_folder = 'application';

$system_path và $application_folder là 2 biến mà codeigniter sẽ dùng để tìm thư mục system và application tương ứng, bạn cần sửa nó để nó trỏ đúng thư mục application và system mà bạn vừa copy khi nãy. Thay đổi như bên dưới:


/*
 *---------------------------------------------------------------
 * SYSTEM FOLDER NAME
 *---------------------------------------------------------------
 *
 * This variable must contain the name of your "system" folder.
 * Include the path if the folder is not in the same  directory
 * as this file.
 *
 */
 $system_path = '../codeigniter/system';

/*
 *---------------------------------------------------------------
 * APPLICATION FOLDER NAME
 *---------------------------------------------------------------
 *
 * If you want this front controller to use a different "application"
 * folder then the default one you can set its name here. The folder
 * can also be renamed or relocated anywhere on your server.  If
 * you do, use a full server path. For more info please see the user guide:
 * http://codeigniter.com/user_guide/general/managing_apps.html
 *
 * NO TRAILING SLASH!
 *
 */
 $application_folder = '../codeigniter/application';

Default đường dẫn của Codeigniter sẽ có "index.php/" để bỏ đi cái index.php này khỏi url cho đẹp (giống như website danlaptrinh.com này này) thì bạn cần tạo ra 1 file .htaccess với nội dung như sau:


 RewriteEngine on
 RewriteCond $1 !^(index\.php|images|robots\.txt)
 RewriteRule ^(.*)$ /index.php/$1 [L]

lưu file .htaccess vào thư mục gốc cạnh index.php (public_html, www). Trong bài viết này chúng ta không đi sâu vào việc .htaccess hoạt động ra sao, có thể sẽ trong một bài khác nhé.

Cuối cùng, chúng ta sẽ cấu hình codeigniter để load thư viện database. Mở file /codeigniter/application/config/autoload.php. Ở dòng 43 bạn sẽ thấy như bên dưới:

 /*
 | -------------------------------------------------------------------
 |  Auto-load Libraries
 | -------------------------------------------------------------------
 | These are the classes located in the system/libraries folder
 | or in your application/libraries folder.
 |
 | Prototype:
 |
 | $autoload['libraries'] = array('database', 'session', 'xmlrpc');
 */

 $autoload['libraries'] = array();

BẠn chỉ cần thêm 'database' vào array(), như code bên dưới:



 /*
 | -------------------------------------------------------------------
 |  Auto-load Libraries
 | -------------------------------------------------------------------
 | These are the classes located in the system/libraries folder
 | or in your application/libraries folder.
 |
 | Prototype:
 |
 | $autoload['libraries'] = array('database', 'session', 'xmlrpc');
 */

 $autoload['libraries'] = array('database');

Bây giờ thì bạn đã sẵn sàng thao tác với thư viện database rồi. Bước đầu coi như xong! bật web server lên,Bây giờ bạn vào web browser trỏ tới web của bạn bạn sẽ thấy dòng Welcome của Codeigniter như bên dưới:

Welcome to Codeingiter

Lúc này thì tôi sẽ giải thích một chút tại sao tôi lại hướng dẫn các bạn đặt thư mục application và system ở ngoài thư mục gốc. Làm như vậy về mặt bảo mật sẽ tốt hơn nhiều việc để trong thư mục web root, không ai biết và có thể truy cập và xem code system hay code application của bạn (thực ra thì codeigniter đã có phương án để người khác chẳng thể show và tìm hiểu cấu trúc code của bạn đâu, nhưng cẩn thận còn hơn hãy làm cho thành thói quen)

Bây Giờ Chúng Ta Sẽ Đề CậP ĐếN Model.

MVC viết tắt của Model, View và Controller. Như trước tôi đã đề cập thì bài này không đi sâu vào phân tích về mô hình MVC, Bạn chỉ cần biết rằng MVC là cách tổ chức code của bạn làm cho code của bạn dễ phát triển, dễ sửa lỗi và mở rộng hơn.

  • Model – Các model là các class mà bạn sẽ dùng để truy cập trực tiếp với database. Mặc dù không bắt buộc, nhưng bạn nên làm như thế. Đừng phá vỡ cấu trúc bằng cách truy cập database từ Controller nhé.
  • View – là các file HTML và các code php để trình bày giao diện người dùng. Bạn không nên code quá nhiều logic hay database ở dây. Nói chung là chỉ dùng views để trình bày giao diện web thôi.
  • Controller – Business logic sẽ code ở đây, nói dễ hiểu nó là con điều phối viên, giao tiếp với database thông qua models và trao đổi data với các views. (nhận data từ người dung, truyền data để hiển thị trên view)

Trước khi tạo model chúng ta trước tiên tạo 1 database đã nhé. Chạy SQL sau:


 --
 -- Table structure for table `user`
 --

 CREATE TABLE IF NOT EXISTS `user` (
   `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
   `username` varchar(128) NOT NULL,
   `password` varchar(128) NOT NULL,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

 INSERT INTO `user` (`id`, `username`, `password`) VALUES (NULL, 'Gandalf', 'iamwhite!'), (NULL, 'Bilbo', 'bagginses!'), (NULL, 'Gollum', 'precious'), (NULL, 'arwen', 'tolodannangalad');

Đoạn SQL trên tạo ra 1 bảng user đơn giản, lưu thông tin user, ở đây là username và password, thêm 1 cái id tự tăng nữa. Bây giờ chúng ta cấu hình database để codeigniter biết truy cập vào database nào.

mở file /codeigniter/application/config/database.php ở dòng 51 bạn sẽ thấy:


 $db['default']['hostname'] = 'localhost';
 $db['default']['username'] = '';
 $db['default']['password'] = '';
 $db['default']['database'] = '';
 $db['default']['dbdriver'] = 'mysql';
 $db['default']['dbprefix'] = '';
 $db['default']['pconnect'] = TRUE;
 $db['default']['db_debug'] = TRUE;
 $db['default']['cache_on'] = FALSE;
 $db['default']['cachedir'] = '';
 $db['default']['char_set'] = 'utf8';
 $db['default']['dbcollat'] = 'utf8_general_ci';
 $db['default']['swap_pre'] = '';
 $db['default']['autoinit'] = TRUE;
 $db['default']['stricton'] = FALSE;

Chúng ta cần thay đổi 3 trường là username, password và database. Xem bên dưới, ở đây username, password là username password db của bạn, thông thường với web mục đích học thì sẽ dùng root và password trống, database là db mà bạn đã tạo.


 $db['default']['hostname'] = 'localhost';
 $db['default']['username'] = '[USERNAME]';
 $db['default']['password'] = '[PASSWORD]';
 $db['default']['database'] = 'tutorial';
 $db['default']['dbdriver'] = 'mysql';
 $db['default']['dbprefix'] = '';
 $db['default']['pconnect'] = TRUE;
 $db['default']['db_debug'] = TRUE;
 $db['default']['cache_on'] = FALSE;
 $db['default']['cachedir'] = '';
 $db['default']['char_set'] = 'utf8';
 $db['default']['dbcollat'] = 'utf8_general_ci';
 $db['default']['swap_pre'] = '';
 $db['default']['autoinit'] = TRUE;
 $db['default']['stricton'] = FALSE;

Bây giờ chúng ta sẽ tạo model để dùng truy cập vào bảng user.


/**
 * Includes the User_Model class as well as the required sub-classes
 * @package codeigniter.application.models
 */

/**
 * User_Model extends codeigniters base CI_Model to inherit all codeigniter magic!
 * @author Leon Revill
 * @package codeigniter.application.models
 */
class User_Model extends CI_Model
{
 /*
 * A private variable to represent each column in the database
 */
 private $_id;
 private $_username;
 private $_password;

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

 /*
 * SET's & GET's
 * Set's and get's allow you to retrieve or set a private variable on an object
 */


 /**
  ID
 **/

 /**
 * @return int [$this->_id] Return this objects ID
 */
 public function getId()
 {
  return $this->_id;
 }

 /**
 * @param int Integer to set this objects ID to
 */
 public function setId($value)
 {
  $this->_id = $value;
 }

 /**
  USERNAME
 **/

 /**
 * @return string [$this->_username] Return this objects username
 */
 public function getUsername()
 {
  return $this->_username;
 }

 /**
 * @param string String to set this objects username to
 */
 public function setUsername($value)
 {
  $this->_username = $value;
 }

 /**
  PASSWORD
 **/

 /**
 * @return string [$this->_password] Return this objects password
 */
 public function getPassword()
 {
  return $this->_password;
 }

 /**
 * @param string String to set this objects password to
 */
 public function setPassword($value)
 {
  $this->_password = $value;
 }

 /*
 * Class Methods
 */

 /**
 * Commit method, this will comment the entire object to the database
 */
 public function commit()
 {
  $data = array(
   'username' => $this->_username,
   'password' => $this->_password
  );

  if ($this->_id > 0) {
   //We have an ID so we need to update this object because it is not new
   if ($this->db->update("user", $data, array("id" => $this->_id))) {
    return true;
   }
  } else {
   //We dont have an ID meaning it is new and not yet in the database so we need to do an insert
   if ($this->db->insert("user", $data)) {
    //Now we can get the ID and update the newly created object
    $this->_id = $this->db->insert_id();
    return true;
   }
  }
  return false;
 }
}

Lưu đoạn code trên vào file user_model.php ở bên trong thư mục /codeigniter/application/models

Tất cả chúng ta cần cho 1 model chỉ có thế! Đi vào chi tiết một chút

Các BiếN Private


 private $_id;
 private $_username;
 private $_password;

Các biến này để lưu thông tin 1 row datababse, bạn thích đặt tên thế nào tùy bạn, nhưng để tránh nhầm lẫn thì nên đặt giống với cột trong db

Các hàm Set và Get


 public function getUsername()
 {
  return $this->_id;
 }

 public function setUsername($value)
 {
  $this->_username = $value;
 }

Lưu database


 public function commit()
 {
  $data = array(
   'username' => $this->_username,
   'password' => $this->_password
  );

  if ($this->_id > 0) {
   //We have an ID so we need to update this object because it is not new
   if ($this->db->update("user", $data, array("id" => $this->_id))) {
    return true;
   }
  } else {
   //We dont have an ID meaning it is new and not yet in the database so we need to do an insert
   if ($this->db->insert("user", $data)) {
    //Now we can get the ID and update the newly created object
    $this->_id = $this->db->insert_id();
    return true;
   }
  }
  return false;
 }

Chúng ta tạo 1 hàm commit để lưu thông tin user vào database, hàm này check nếu nó có id thì update row, nếu không thì sẽ insert row mới vào database.

Model Factory

Chúng ta sẽ tạo một class đơn giản với 2 hàm getUser, createUser, Hãy xem đoạn code bên dưới:


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

class UserFactory {

 private $_ci;

  function __construct()
    {
     //When the class is constructed get an instance of codeigniter so we can access it locally
     $this->_ci =& get_instance();
     //Include the user_model so we can use it
     $this->_ci->load->model("user_model");
    }

    public function getUser($id = 0) {
     //Are we getting an individual user or are we getting them all
     if ($id > 0) {
      //Getting an individual user
      $query = $this->_ci->db->get_where("user", array("id" => $id));
      //Check if any results were returned
      if ($query->num_rows() > 0) {
       //Pass the data to our local function to create an object for us and return this new object
       return $this->createObjectFromData($query->row());
      }
      return false;
     } else {
      //Getting all the users
      $query = $this->_ci->db->select("*")->from("user")->get();
      //Check if any results were returned
      if ($query->num_rows() > 0) {
       //Create an array to store users
       $users = array();
       //Loop through each row returned from the query
       foreach ($query->result() as $row) {
        //Pass the row data to our local function which creates a new user object with the data provided and add it to the users array
        $users[] = $this->createObjectFromData($row);
       }
       //Return the users array
       return $users;
      }
      return false;
     }
    }

    public function createObjectFromData($row) {
     //Create a new user_model object
     $user = new User_Model();
     //Set the ID on the user model
     $user->setId($row->id);
     //Set the username on the user model
     $user->setUsername($row->username);
     //Set the password on the user model
     $user->setPassword($row->password);
     //Return the new user object
     return $user;
    }

}

Đoạn code trên đã được comment rất rõ ràng, để các bạn có thể hiểu được đoạn code đó làm gì.

Đầu tiên cần lưu ý đoạn code sau:


 private $_ci;

  function __construct()
    {
     //When the class is constructed get an instance of codeigniter so we can access it locally
     $this->_ci =& get_instance();
     //Include the user_model so we can use it
     $this->_ci->load->model("user_model");
    }

Chúng ta tạo một biến private $_ci, viết tắt của codeigniter là biết để lưu instance của codeigniter thông qua biến này chúng ta access các resource của nó.

Sau đó trong hàm khởi tạo __construct() chúng ta gọi hàm tạo codeigniter instance và lưu vào biến _ci. Bây giờ chúng ta có thể sử dụng _ci một cách thoải mái, ví dụ: $this->_ci->db->select(“*”)->from(“user”)->get();

Trong class factory chúng ta có 2 hàm, hàm quan trọng là hàm getUser:


public function getUser($id = 0) {
     //Are we getting an individual user or are we getting them all
     if ($id > 0) {
      //Getting an individual user
      $query = $this->_ci->db->get_where("user", array("id" => $id));
      //Check if any results were returned
      if ($query->num_rows() > 0) {
       //Pass the data to our local function to create an object for us and return this new object
       return $this->createObjectFromData($query->row());
      }
      return false;
     } else {
      //Getting all the users
      $query = $this->_ci->db->select("*")->from("user")->get();
      //Check if any results were returned
      if ($query->num_rows() > 0) {
       //Create an array to store users
       $users = array();
       //Loop through each row returned from the query
       foreach ($query->result() as $row) {
        //Pass the row data to our local function which creates a new user object with the data provided and add it to the users array
        $users[] = $this->createObjectFromData($row);
       }
       //Return the users array
       return $users;
      }
      return false;
     }
 }

Hàm này truyền 1 tham số là $id để chúng ta lấy ra user tương ứng hoặc nếu không truyền tham số chúng ta sẽ lấy ra tất cả các user trong bảng user. Hãy lướt qua đoạn code trông có vẻ phức tạp một chút đó là đoạn lấy tất cả user:


 //Getting all the users
 $query = $this->_ci->db->select("*")->from("user")->get();
 //Check if any results were returned
 if ($query->num_rows() > 0) {
  //Create an array to store users
  $users = array();
  //Loop through each row returned from the query
  foreach ($query->result() as $row) {
   //Pass the row data to our local function which creates a new user object with the data provided and add it to the users array
   $users[] = $this->createObjectFromData($row);
  }
  //Return the users array
  return $users;
 }
 return false;

Đầu tiên chúng ta query bảng user và lấy tất cả các rows ($query = $this->_ci->db->select(“*”)->from(“user”)->get();). Sau đó check kết quả $query->num_rows() hàm này trả về số lượng records trả về. Nếu kết quả là 0 records ta trả về false. Nếu lơn hơn 0 chúng ta tạo ra 1 mảng users sau đó chạy vòng lặp tất cả các row: foreach ($query->result() as $row) {.

Mỗi kết quả chúng a gọi hàm:


    public function createObjectFromData($row) {
     //Create a new user_model object
     $user = new User_Model();
     //Set the ID on the user model
     $user->setId($row->id);
     //Set the username on the user model
     $user->setUsername($row->username);
     //Set the password on the user model
     $user->setPassword($row->password);
     //Return the new user object
     return $user;
    }

Mỗi hàm sẽ lấy data của một row, và tạo 1 object user_model để lưu data này (mỗi model là 1 row nhé) sau đó mỗi object đó được lưu vào mảng $users. Sau khi duyệt hết thì chúng ta có một mảng $users chứa các objects là các model tương ứng với mỗi row. Đơn giản đúng không!

Để sử dụng class factory này chúng ta sẽ sử dụng nó như 1 thư viện nhé, lưu vào trong thư mục /codeigniter/application/libraries

Controllers

Một controller là phần sẽ quyết định hiển thịc cái gì và hiển thị như thế nào. Ta hãy tạo một file users.php trong /codeingiter/application/controllers như bên dưới:


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

class Users extends CI_Controller {

 public function index()
 {
  echo "This is the index!";
 }

 public function show($userId = 0)
 {
  $userId = (int)$userId;
  echo "This is show users!";
  if ($userId > 0) {
   echo "User ID: {$userId}";
  }
 }
}

Đây chưa phải là code cuối cùng nhưng chúng ta sẽ sử dụng nó để giúp bạn hiểu cách thức làm việc của controller trong codeIgniter. Bây giờ bạn hãy mở trình duyệt và mở trang của bạn nhé trong trường hợp này hãy vào: http://localhost:8080/users bạn sẽ thấy màn hình như dưới đây:

Codeigniter controller index

Hàm index trong controller sẽ là hàm mà controller sẽ chọn nếu bạn không chỉ định hàm nào trong url. bây giờ hay vào: http://localhost:8080/users/show bạn sẽ thấy màn hình như bên dưới, bây giờ controller sẽ trỏ tới hàm show:

Codeigniter controller method

Để truyền tham số cho hàm chúng ta vào: http://localhost:8080/users/show/1 bạn sẽ thấy màn hình như bên dưới.

Codeigniter controller method

Bây giờ chắc bạn đã hiểu Controller của codeigniters hoạt động như thế nào rồi, bây giờ chúng ta code tiếp nhé.

Viết hàm show như bên dưới:


 public function show($userId = 0)
 {
  //Always ensure an integer
  $userId = (int)$userId;
  //Load the user factory
  $this->load->library("UserFactory");
  //Create a data array so we can pass information to the view
  $data = array(
   "users" => $this->userfactory->getUser($userId)
  );
  //Dump out the data array
  var_dump($data);
 }

Thông qua các comment ở code này, bạn có thể hiểu đoạn code làm gì rồi. Quan trọng nhất là hàm này load thư viện user factory chúng ta đã tao ở trên, thông qua thư viện này chúng ta get thông tin user. Chúng ta lưu kết quả vào trong 1 mảng, chúng ta sẽ dùng mảng này ở View, còn bây giờ thì chúng ta chỉ dump nó để xem trong đó có gì. Mở đường dẫn: http://localhost:8080/users/show Bạn sẽ thấy dump bên dưới đây:


array(1) { ["users"]=> array(4) { [0]=> object(User_Model)#22 (3) { ["_id":"User_Model":private]=> string(1) "1" ["_username":"User_Model":private]=> string(7) "Gandalf" ["_password":"User_Model":private]=> string(9) "iamwhite!" } [1]=> object(User_Model)#23 (3) { ["_id":"User_Model":private]=> string(1) "2" ["_username":"User_Model":private]=> string(5) "Bilbo" ["_password":"User_Model":private]=> string(10) "bagginses!" } [2]=> object(User_Model)#24 (3) { ["_id":"User_Model":private]=> string(1) "3" ["_username":"User_Model":private]=> string(6) "Gollum" ["_password":"User_Model":private]=> string(8) "precious" } [3]=> object(User_Model)#25 (3) { ["_id":"User_Model":private]=> string(1) "4" ["_username":"User_Model":private]=> string(5) "arwen" ["_password":"User_Model":private]=> string(15) "tolodannangalad" } } }

The above output is a dump of an array of user models which are presenting every user within our user table, if you navigate to: http://localhost:8080/users/show/1 and view the following output:


array(1) { ["users"]=> object(User_Model)#19 (3) { ["_id":"User_Model":private]=> string(1) "1" ["_username":"User_Model":private]=> string(7) "Gandalf" ["_password":"User_Model":private]=> string(9) "iamwhite!" } }

Bây giờ bạn đã hiểu khá rõ hoạt động của codeigniter rồi. Bây giờ đến giai đoạn cuối cùng là tạo views!

Views

TạO 1 File Show_Users.Php Trong Thư MụC /Codeingiter/Application/Views VớI ĐoạN Code Như Sau:


 //Check to see if users could be found
 if ($users !== FALSE) {

  //Create the HTML table header
  echo <<

ID # Username Password HTML;

//Do we have an array of users or just a single user object? if (is_array($users) && count($users)) { //Loop through all the users and create a row for each within the table foreach ($users as $user) { echo <<

{$user->getId()} {$user->getUsername()} {$user->getPassword()} HTML;

} } else { //Only a single user object so just create one row within the table echo <<

{$users->getId()} {$users->getUsername()} {$users->getPassword()} HTML;

} //Close the table HTML echo <<

HTML;

} else { //Now user could be found so display an error messsage to the user echo <<

A user could not be found with the specified user ID#, please try again.

HTML;

}

Trước khi xem xét kỹ đoan code trên, chúng ta trước hết hãy cập nhật controllers để load views tương ứng, và truyền dữ liệu cần thiết cho nó, thay đổi code như bên dưới:


 public function show($userId = 0)
 {
  //Always ensure an integer
  $userId = (int)$userId;
  //Load the user factory
  $this->load->library("UserFactory");
  //Create a data array so we can pass information to the view
  $data = array(
   "users" => $this->userfactory->getUser($userId)
  );
  //Load the view and pass the data to it
  $this->load->view("show_users", $data);
 }

Chúng ta gọi hàm load của codeigniter $this->load->view() để load view mà chúng ta đã tạo ở trên. Tham số đầu tiên là tên file views trong thư mục application/views, tham số thứ 2 là mảng các dữ liệu mà ta cần truyền cho views. Lưu ý là tất cả các key của mảng $datasẽ trở thành biến được sử dụng trong views. Trong ví dụ này ta truyền $data["users"] ở views thì chúng ta chỉ cần dùng $users để truy cập dữ liệu này.

Bây giờ chúng ta đã load view, và hiểu làm sao để truy cập dữ liệu từ controller ở views. Thử lướt qua code của views nhé.

Đầu tiên chúng ta kiểm tra $users xem có phải false không, nếu factory không tìm thấy user tương ứng với id, nó sẽ trả về false. Trong trường hợp đó chúng ta hiển thị message: “A user could not be found with the specified user ID#, please try again.”.

Nếu $users khác false chúng ta cần phải check xem nó là mảng hay là 1 row duy nhất. Nếu là một mảng user, chúng ta sẽ duyệt vòng lặp tất cả các user và hiển thị all user vào một table.

Nếu nó chỉ là 1 row duy nhất thì ta chỉ tạo ra và hiển thị 1 row thôi. Đơn giản thế thôi, các bạn thử xem!

ThảO LuậN

Bây giờ nếu bạn tự mình hoàn thành tutorial này bạn sẽ hiểu cách thức làm việc của codeigniter . Bạn biết bắt đầu 1 dự án với codeigniter như thế nào. Trong quá trình làm nếu có vấn đề gì, các bạn hãy đặt câu hỏi, và phản hồi cho chúng tôi nhé. Nếu có gì chưa tốt chúng tôi sẽ ghi nhận và cập nhật. Chúc các bạn tìm được một framework phù hợp.

Source code của Tutorial này có thể download tại đây