相关代码https://github.com/LittleFiveSmile/CI_Post_Demo
基础知识:
CodeIgniter是基于MVC的模式设计
MVC 指的是Model -View -Controller
- Model:模式。一般用来写具体的功能(如实现算法、数据库的更新等)
- View:视图。通常是web的页面。在view中也可以把页面拆分成几个部分 比header和footer 从而实现类似于模板语言的功能。
- Controller:控制。负责连接 model 和view。将view里面的请求转发到model里面进行处理
CodeIgniter的文件目录中 这三个部分分别存储在application里面的controllers,models和views三个文件夹中
示例:
假如我们现在要实现在网站发布帖子的功能,这里分成三个部分:
1. Model部分:
models/Post_model.php 中就有 get_posts(),create_post(),delete_post(),和update_post()这四种功能
<?php
class Post_model extends CI_Model{
public function __construct()
{
$this->load->database();
}
public function get_posts($slug =FALSE){
if($slug ===FALSE){
$this -> db ->order_by('id','DESC');
$query = $this ->db ->get('posts');
return $query -> result_array();
}
$query = $this->db ->get_where('posts',array('slug' => $slug));
return $query->row_array();
}
public function create_post(){
$slug = url_title($this ->input->post('title'));
$data = array(
'title' =>$this ->input ->post('title'),
'slug' =>$slug,
'body' => $this -> input ->post('body')
);
return $this -> db -> insert('posts',$data);
}
public function delete_post($id){
$this->db->where('id',$id);
$this ->db->delete('posts');
return true;
}
public function update_post(){
$slug = url_title($this ->input->post('title'));
$data = array(
'title' =>$this ->input ->post('title'),
'slug' =>$slug,
'body' => $this -> input ->post('body')
);
$this ->db->where('id',$this ->input->post('id'));
return $this -> db -> update('posts',$data);
}
}
2. View 部分
在views/posts/create.php里面是用户可以看得到的页面
<h2><?= $title;?></h2>
<?php echo validation_errors();?>
<!--<form>-->
<?php echo form_open('index.php/posts/create');?>
<fieldset>
<div class="form-group">
<label >Title</label>
<input type="text" class="form-control" name="title" placeholder="Add Title">
</div>
<div class="form-group">
<label >Body</label>
<textarea id="editor1" class="form-control" name="body" placeholder="Add Body" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</form>
在上面的代码中你会注意到这一句
<?php echo form_open('index.php/posts/create');?>
这里调用了 posts 这个controller里面的create 这个class,那么它是如何通过它控制model里面的具体的功能呢?
所以我们需要下面的controller进行控制
3.Ccontroller部分
在Controller/Posts.php中
<?php
class Posts extends CI_Controller {
public function create(){
$data['title'] = 'Create Post';
$this ->form_validation ->set_rules('title','Title','required');
$this ->form_validation ->set_rules('body','Body','required');
if($this -> form_validation ->run() === FALSE){
$this ->load ->view('templates/header');
$this ->load ->view('posts/create',$data);
$this ->load ->view('templates/footer');
} else{
$this -> post_model ->create_post();
redirect('index.php/posts');
}
}
}
如果 form_validation检查无误的话就会执行else{}语句
$this -> post_model ->create_post();
在这里就调用了最一开始我提到的Model里面的create_post这个功能。