codeigniter:用 CodeIgniter 开发动态 Web 站点

  CodeIgniter 是种以 PHP 编写开源 Web 应用框架它可适用于很多种数据库应用包括 MySQL、DB2® Express-C 等此框架使用是 MVC 设计模式其最主要是分离个软件Software应用数据层和表示层在 Model-View-Controller (MVC) 模式中model 管理数据层和数据库通信;view 管理表示层显示 UI 和内容;而 controller 则负责管理视图和模型的间通信

  常用缩略词

  CRUD:创建、读取、更新、删除

  HTML:超文本标记语言

  MVC:模型-视图-控制器

  SQL:结构化查询语言

  UI:用户界面

  本文概述了使用 CodeIgniter 创建个基础动态 Web 站点或应用所需步骤本文假设您已经安装了 CodeIgniter V1.7.2 或更高版本以及 MySQL V4.1 或更高版本并且对 2者有基本了解

  站点基础:小部件和 CRUD

  当然大多数动态 Web 站点都不会等同于本文中所使用这个例子 — 在很多情况下甚至会有显著差别不过所有动态 Web 站点都具有两个关键共同点:数据库以及从该数据库(动态地)检索到东西为了方便本文讨论我将这种可动态检索到东西称为是个小部件个小部件可以是几乎任何内容 — 本在售书、个菜谱、个博客条目或篇新闻稿不管这个小部件是什么其定义都需要组连贯信息例如个菜谱所需组信息可能应该包括个标题、配料、操作指导和营养分析

  要从数据库中检索小部件首先必须要创建它(然后它才可以被更新甚至是删除)这就是所谓 CRUDCRUD 代表是管理数据库内小部件所需最主要 4个操作;若再加上小部件本身实际上就构成了动态 Web 站点基础

  设置数据库

  在本文中我们将创建个 Web 应用来管理组学生及其家长联系信息比如孩子所在体育队、YMCA 小组或学校班级这些都是我们将要创建

  首先创建这个小部件数据模型这个小部件所需组信息如下:

  学生姓名

  家长姓名

  地址

  城市

  州

  ZIP 或邮政编码

  电话号码

  电子邮件地址

  为了存储这个小部件创建个表名为 student内含和如上所列这组信息相对应字段用来创建这个 MySQL 数据库和表脚本如清单 1 所示

清单 1. MySQL 数据库和表创建脚本

CREATE DATABASE room; 
 
USE room; 
 
CREATE TABLE IF NOT EXISTS `student` ( 
 `id` (11) NOT NULL AUTO_INCREMENT, 
 `s_name` varchar(64) DEFAULT NULL, 
 `p_name` varchar(64) DEFAULT NULL, 
 `address` varchar(128) DEFAULT NULL, 
 `city` varchar(32) DEFAULT NULL, 
 `state` char(2) DEFAULT NULL, 
 `zip` char(10) DEFAULT NULL, 
 `phone` char(20) DEFAULT NULL, 
 `email` varchar(64) DEFAULT NULL, 
 PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 


   CodeIgniter 设置

  创建了数据库和表后在 .\system\application\config\database.php 内设置 CodeIgniter 数据库变量在 .\system\application\config\config.php 内设置基础 URL对于本文我假设这个基础 URL 是 http://127.0.0.1/codeigniter/

  默认控制器和视图

  接下来创建个默认控制器和视图(它们就绪后您将能够看到所编写代码效果)对于本项目在 .\system\application\controllers\ 文件夹内创建个名为 student.php 控制器如清单 2 所示并在 .\system\application\config\routes.php 内将其设置为默认控制器

清单 2. 默认控制器:Student

<?php 
 
 Student extends Controller { 
 
 function Student 
 { 
  parent::Controller;  
 } 
  
 function index 
 { 
  // display information for the view 
  $data['title'] = "Classroom: Home Page"; 
  $data['headline'] = "Welcome to the Classroom Management "; 
  $data[''] = 'student_index'; 
 
  $this->load->view('template', $data); 
 } 
} 
 
/* End of file student.php */ 
/* Location: ./system/application/controllers/student.php */ 


  注意index 创建了个名为 data 包含 3个已命名索引:title、 headline 和 被传递给个名为 template 视图该视图被存储为 .\system\application\views\ 文件夹内 template.php(参见清单 3)

清单 3. 默认视图:template.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 
<head> 
<meta http-equiv="content-type" content="text/html; char=UTF-8" /> 
 
<title><?php echo $title;?></title> 
</head> 
<body> 
 
<h1><?php echo $headline;?></h1> 
 
<?php $this->load->view($);?> 
 
</body> 
</html> 


  此视图将是该 Web 站点内所有页面 HTML shell 或可视包装器它包含个标准 HTML 设置并接受来自控制器 3个值 — title、 headline 和 — 分别对应于页面标题、页面大标题以及个用于内容显示视图文件

  这个包含视图文件是设置最后个步骤将其命名为 student_index.php正如在 template.php 内所声明那样(如上面 清单 2 所示)并将其存储在 .\system\application\views\ 文件夹内清单 4 提供了它源代码

清单 4. 些基本 “Hello World” 文本

<p>Congratulations. Your initial up is complete!</p> 

  请注意这里没有标准 HTML 结构标签这是 student_index.php 是通过 template.php 视图包括进来因而是该视图 HTML 包装器和显示部分

  现在如果导航到 http://127.0.0.1/codeigniter/浏览器会载入个页面此页面具有个页面标题、个表示欢迎大标题和条祝贺消息

   4种 CRUD 操作

  让我们从 CRUD 操作角度来分析这个 Web 应用

  创建小部件

  现在设置已经完成了我们需要编写用来管理小部件代码以这 4种 CRUD 操作中个操作开始:创建操作该代码必须将用户输入保存为此数据库内个小部件

  首先创建个 HTML 表单表单字段对应于这个 student 表结构在 .\system\application\views\ 文件夹内创建个名为 student_add.php 视图文件如清单 5 所示

清单 5. 为创建操作生成 HTML 表单字段

<?php 
 
echo form_open('student/create'); 
 
// an .gif' /> of the fields in the student table 
$field_.gif' /> = .gif' />('s_name','p_name','address','city','state','zip','phone','email'); 
foreach($field_.gif' /> as $field) 
{ 
 echo '<p>' . $field; 
 echo form_input(.gif' />('name' => $field)) . '</p>'; 
} 
 
// not ting the value attribute omits the submit from the $_POST .gif' /> 
echo form_submit('', 'Add'); 
 
echo form_close; 
 
?> 


  此文件有两点需要注意它使用了 form_input 是 CodeIgniter Form Helper 部分也是生成大多数表单所需 HTML 种十分快捷方式它接受 3个参数:个字段名、个字段值以及任何额外数据(比如 JavaScript)

  CodeIgniter cut

  在开始个项目或对其进行原型设计时我会使用 CodeIgniter 提供很多内置cut”(比如 HTML Table 类以及 Form 和 URL 帮助文件)来减少编码和调试时间当然其代价是对布局或观感控制将会比较粗糙但在这些早期阶段应当取代表单

  第 2点需要注意是 form_submit 也接受同样 3个参数并具有个针对字段名空白这就可以防止提交字段成为表单发布部分在向数据库添加记录时此模型会使用该;若包括了 submit 字段那么数据库插入就会失败

  然后需要向 Student 控制器(清单 6)添加以便能够看到这个 HTML 表单

清单 6. Student 控制器 add

 function add 
 { 
  $this->load->helper('form'); 
   
  // display information for the view 
  $data['title'] = "Classroom: Add Student"; 
  $data['headline'] = "Add a New Student"; 
  $data[''] = 'student_add'; 
 
  $this->load->view('template', $data); 
 } 


  请注意加载 CodeIgniter Form Helper 以供 student_add.php 视图所用

  现在如果导航到 http://127.0.0.1/codeigniter/index.php/student/add浏览器就会加载这个 HTML 表单其中各字段代表着 student 表内条记录如果提交此表单就会得到我们尚未创建来接收此表单发布为此向 Student 控制器添加个 create 如清单 7 所示

清单 7. Student 控制器 create

 function create 
 { 
  $this->load->helper('url'); 
   
  $this->load->model('MStudent','',TRUE); 
  $this->MStudent->addStudent($_POST); 
  redirect('student/add','refresh'); 
 } 


  此对应于 URL http://127.0.0.1/codeigniter/index.php/student/create它首先加载个称为 MStudent 模型(此模型在下个步骤创建)然后它会执行 addStudent 传递进在 student_add.php 页面上创建 post 最后它会使用 redirect (URL Helper 文件部分)将用户重定向回 student_add.php 页面

  MStudent 模型负责和数据库内 student 表进行交互在 .\system\application\models 文件夹创建个文件名为 mstudent.php(种好做法是在文件名的前或的后添加个能表明该文件是个模型前缀或后缀比如 m)其代码如清单 8 所示

清单 8. 负责数据层 MStudent 模型

<?php 
 
 MStudent extends Model{ 
 
 // Create student record in database 
 function addStudent($data) 
 { 
  $this->db->insert('student', $data); 
 } 
 
} 
 
/* End of file mstudent.php */ 
/* Location: ./system/application/models/mstudent.php */ 


  此模型使用 db->insert 来向 student 表插入 post 数据接受两个参数:表名称以及字段名和值关联是 CodeIgniter Active Record 类部分会自动加载并且是 CodeIgniter 提供 cut 的可减少开发时间

  并且正如的前提到如果 post 将 Submit 按钮作为个字段包括进来那么插入就会失效在此表内没有个名为 submit 字段

  再次导航到 http://127.0.0.1/codeigniter/index.php/student/add这次将某些数据放入这些字段并单击 Submit页面将会刷新并且字段也会被置空但是如果查看下该数据库就会看到所提交数据已经被添加到这个 student 表

  检索小部件

  第 2个 CRUD 操作是读取代码作用是从数据库中读取小部件记录当然经常还需要显示这些记录这也是为什么人们更愿意将这种操作称为检索 原因

  首先更新 MStudent 模型以便检索 student 表记录如清单 9 所示

清单 9. MStudent 用来检索学生记录

 // Retrieve all student records 
 function listStudents 
 { 
   $this->db->get('student'); 
 } 


  上述代码使用了 db->get (该也是 CodeIgniter Active Record 类部分)来生成个 SELECT *它针对在参数(student)内命名

  接下来向 Student 控制器添加名为 listing用来加载 MStudent 模型并执行 listStudents 如清单 10 所示

清单 10. 创建 HTML 表来显示学生记录

 function listing 
 { 
  $this->load->library('table'); 
   
  $this->load->model('MStudent','',TRUE); 
  $students_qry = $this->MStudent->listStudents; 
 
  // generate HTML table from query results 
  $students_table = $this->table->generate($students_qry); 
   
  // display information for the view 
  $data['title'] = "Classroom: Student Listing"; 
  $data['headline'] = "Student Listing"; 
  $data[''] = 'student_listing'; 
 
  $data['data_table'] = $students_table; 
 
  $this->load->view('template', $data); 
 } 


  此在 HTML Table 类内使用了 table->generate (个 CodeIgniter cut)它生成了个 HTML 表并且以来自查询结果对象字段名作为表标题行的后每条记录依次列出其结果以数据形式传递给模板视图

  最后需要个视图来显示这个 HTML 表在 .\system\application\views\ 文件夹内创建个名为 student_listing.php 文件如清单 11 所示

清单 11. 显示 HTML 表

<?php echo $data_table; ?> 

  要查看此操作结果访问 http://127.0.0.1/codeigniter/index.php/student/listing您将会看到从此数据库中检索到学生列表现在通过使用输入表单添加更多学生记录或运行如清单 12 所示 SQL 脚本实现相同

清单 12. 用来添加学生记录 SQL 脚本

INSERT INTO room.student 
 (id, s_name, p_name, address, city, state, zip, phone, email) 
 VALUES 
(NULL, 'Peter Green', 'Len & Natalie Green', '480 West Broad Street', 
 'Eastbrook Canyon', 'PA', '19104', '(215) 900-2341', 
 '[email protected]'), 
(NULL, 'Jonah Ross', 'Robert & Linda Ross', '1293 Law Street', 
 'Eastbrook Village', 'PA', '19105', '(215) 907-1122', '[email protected]'), 
(NULL, 'Rebecca Dillon', 'Lainie and Howard Dillon', '12 Flamingo Drive', 
 'Westbrook Village', 'PA', '19103', '(215) 887-4313', '[email protected]'), 
(NULL, 'Noah Singer', 'Carolyn & Peter Singer', '393 Green Lake Road, 8th Floor', 
 'Eastbrook Village', 'PA', '19105', '(215) 907-2344', '[email protected]'), 
(NULL, 'Trevor Lee Logan', 'Steven Logan', '400 Green Lake Road, 9th Floor', 
 'Eastbrook Village', 'PA', '19105-6541', '(828) 299-9885', 
 '[email protected]'), 
(NULL, 'Audrey Christiansen', 'Lovey Christiansen', '1993 East Sunnyside Lane', 
 'Eastbrook Canyon', 'PA', '19104', '(215) 887-5545', 
 '[email protected]'); 


  在转入下个 CRUD 操作的前为了让导航站点更为简便可以在 .\system\application\views 文件夹内 template.php 文件中 <h1> 标签的上添加组全局导航链接代码如清单 13 所示

清单 13. 全局导航链接

<div ="navigation"> 
<?php 
 // nav bar 
 echo anchor('student/index', 'Home'); 
 echo (' | '); 
 echo anchor('student/add', 'Add a New Student'); 
 echo (' | '); 
 echo anchor('student/listing', 'List All Students'); 
?> 
</div> 


  此代码使用了 anchor cut它也是 CodeIgniter URL Helper 文件部分并且由于 Student 控制器内每个都会接触到模板视图所以需要加载 URL Helper作为 Student 构造部分(参见清单 14)此外还应该从 create 删除它以避免两次加载 Helper 文件

清单 14. 在个构造内加载个 helper

 function __construct 
 { 
  parent::Controller; 
 
  // load helpers 
  $this->load->helper('url'); 
 } 


  更新小部件

  现在可以进行第 3个 CRUD 操作:更新对此代码必须:

  从数据库读取个小部件记录

  显示该记录以便编辑

  允许用户将更新后信息提交回数据库

  首先更新学生列表以便在每行都包括个 Edit 选项仍可以使用 HTML Table 类来生成此表所需大多数 HTML不过现在需要显式地对数据库查询结果对象进行循环以便创建这些表行并添加 Edit 选项对 Student 控制器内 listing 更新详见清单 15

清单 15. 使用 HTML Table 类创建个表

  // generate HTML table from query results 
  $tmpl = .gif' /> ( 
   'table_open' => '<table border="0" cellpadding="3" cellspacing="0">', 
   'heading_row_start' => '<tr bgcolor="#66cc44">', 
   'row_start' => '<tr bgcolor="#dddddd">' 
   ); 
  $this->table->_template($tmpl); 
   
  $this->table->_empty("&nbsp;"); 
  
  $this->table->_heading('', 'Child Name', 'Parent Name', 'Address', 
    'City', 'State', 'Zip', 'Phone', 'Email'); 
  
  $table_row = .gif' />; 
  foreach ($students_qry->result as $student) 
  { 
   $table_row = NULL; 
   $table_row = anchor('student/edit/' . $student->id, 'edit'); 
   $table_row = $student->s_name; 
   $table_row = $student->p_name; 
   $table_row = $student->address; 
   $table_row = $student->city; 
   $table_row = $student->state; 
   $table_row = $student->zip; 
   $table_row = $student->phone; 
   $table_row = mailto($student->email); 
 
   $this->table->add_row($table_row); 
  }   
 
  $students_table = $this->table->generate; 


Tags:  codeigniter分页 codeigniter教程 codeigniter中文 codeigniter

延伸阅读

最新评论

发表评论