php-ci 学习笔记二(mvc)
controller
class Article extends CI_Controller{ //构造函数 public function __construct(){ parent::__construct(); //引入数据模型 $this->load->model('article/article_model'); //URL处理函数 $this->load->helper('url_helper'); } //默认函数 public function index(){ $data['article']=$this->article_model->get_article(); $this->load->view('templates/header',$data); $this->load->view('article/index',$data); $this->load->view('templates/footer',$data); } //aritcle/url有参数时函数 public function view($slug=NULL){ $data['article_item']=$this->article_model->get_article($slug); //无查询结果时返回404 if(empty($data['article_item'])){ show_404(); } $data['title']=$data['article_item']['title']; $this->load->view('templates/header',$data); $this->load->view('article/view',$data); $this->load->view('templates/footer',$data); } public function create(){ //表单处理 $this->load->helper('form'); $this->load->library('form_validation'); //验证获取的表单数据 $this->form_validation->set_rules('title','Title','required'); $this->form_validation->set_rules('content',"Content",'required'); $this->form_validation->set_rules('tag',"Tag",'required'); //表单验证不同结果返回不同页面 if($this->form_validation->run()===FALSE){ $this->load->view('templates/header',$data); $this->load->view('article/create',$data); $this->load->view('templates/footer',$data); }else{ $this->article_model->set_article(); $this->load->view('article/success'); } } }
Model
在application/config/database.php中修改好数据库连接
class Article_model extends CI_Model{ public function __construct(){ //载入database $this->load->database(); } //查 public function get_article($slug=FALSE){ //无查询参数时 if($slug===FALSE){ $query=$this->db->get('article'); return $query->result_array(); } $query=$this->db->get_where('article',array('id'=>$slug)); return $query->row_array(); } //增 public function set_article(){ $this->load->helper('url'); //url_title用于将字符串 中的所有空格替换成连接符(-),并将所有字符转换为小写 $slug=url_title($this->input->post('title'),'dash',TRUE); $data=array( 'title'=>$this->input->post('title'), //'slug'=>$slug, 'content'=>$this->input->post('content') ); return $this->db->insert('article',$data); } }
view
//验证错误信息 echo validation_errors(); //调用article控制器下的create方法 echo form_open('article/create'); ...