CodeIgniter(CI)学习笔记整理

作者:admin发表时间:2014-8-15 评论:2 点击 5,979+

深入理解MVC设计模式
CI的超级对象
数据库访问

AR模式
如何扩展CI的控制器
模型

uri的相关函数
设置路由
隐藏入口文件
分页
文件上传
session
验证码
表单验证

CI中的MVC
访问url使用的是pathinfo

入口文件.php/控制器/动作

application目录中

controllers 控制器
models 模型
views 视图
 
默认控制器是welcome
默认动作是index

控制器
1.不需要加后缀
2.文件名全部小写 例如user.php
3.所有的控制器,直接或间接继承CI_Controller类
4.控制器中,对动作(方法)要求:
public
不能以_开头

视图
1.在控制器中如果加载视图
//直接写视图名字,不写扩展名,如果有子目录,则写上目录名
$this->load->view(视图);
可以多次调用$this->load->view(视图);
2.视图中,直接使用原生php代码
3.推荐使用
<?php foreach ($showlist->result() as $item): ?>
<?= $item->title ?>
<?php endforeach; ?>

超级对象
当前控制器对象
提供了很多属性:
$this->load
装载器类的实例system/core/loader.php
装载器类提供方法:
view 装载视图
vars() 分配变量到视图
datebase() 装载数据库操作对象
model() 装载模型对象
helper()

$this->uri
是CI_URI类的实例system/core/URI.php
CI_URI类提供方法:
segment(n) 用于获取url中的第n个参数值
传统的:入口文件.php/控制器/动作/参数1/值1/参数2/值2
入口文件.php/控制器/动作/值1/值2
echo $this->uri->segment(3) //值1
echo $this->uri->segment(4) //值2

//index.php/控制器/index/6
public function index($p=0){ echo $p;//输出6}

$this->input
输入类
是CI_Input类的实例system/core/Input.php
CI_Input类提供方法:
$this->input->post(‘username’);  //$_POST[‘username’]
$this->input->sever(‘DOCUMENT_ROOT’);//$_SERVER[‘DOCUMENT_ROOT’]

在视图中,直接用$this来访问超级对象中的属性

数据库访问
修改配置文件
application/config/database.php
将数据库访问对象,装载到超级对象的属性中 $this->db
$this->load->database();
$rs->$this->db->query($sql);//返回对象
$res->result();//返回数组。数组是一个一个的对象
$rs->result_array();//返回二维数组,里面是关联数组
$res->row//返回第一条数据,直接是一个对象

参数绑定
$sql=”select *from blog_user where name=?”;
$this->db-query($sql,$name);//如果有多个问号时,需要传入一个索引数值

表前缀
$db[‘default’][‘dbprefix’]=’blog_’;
$db[‘default’][‘swap_pre’]=’blog_’;

配置为一样,嗲吗中,直接影编码表前缀就行了,如果以后项目数据库表前缀发生变化,只需要修改
$db[‘default’][‘dbprefix’]=’new_’;代码中的blog_会自动替换为new_

db的自动加载

application/config/autoload.php
$autoload[‘libraries’]=array(‘databae’);
不需要:$this->load->database();

自增id
$this->insert_id();
受影响行数
$this->db->affected_rows();
Active Record
1.application/config/database.php
$active_recors=TRUE;
2.application/config/autolaod.php
$sutoload[‘libraries’]=array(‘database’);
3,在配置文件中,配置表前缀后,会自动添加
 
$res->$this->db->get(‘表名’)//返回结果集对象
$res->result();
$bool=$this->db->insert(‘表名’,关联数组);
$bool=$this->db->update(‘表名’,关联数组,条件);
$bool=$this->db->delete(‘表名’,条件);
 
  //select id,name from tableName where id>3 order by id desc limit 2,3
  $res=$this->db->select(‘id,name’)
  ->from(‘user’)
  ->where(‘id >=’,3)
  ->limit(3,2)//跳过2条,取出3条数据
  ->order_by(‘id desc ‘)
  ->get();
 
  //显示最近一条sql
  echo $this->db->last_query();
  //where
  $res->db->where(‘name’,’mary’)->get(‘user’);
  $res->db->where(‘name !=’,’mary’)->get(‘user’);
  $res->db->where(array(‘name’=>’mary’))->get(‘user’);
  $res->db->where(array(‘name’=>’mary’,’id’=>’2′))->get(‘user’);
 
  复杂的查询,使用$this->db->query($sql,$data);//使用问号绑定参数
 
 
  扩展CI控制器
  application/core/MY_Controller.php
  控制器要继承自MY_Controller
  application/config/config.php
  $config[‘subclass_prefix’]=’MY_’;
 
  模型
   继承自CI_modle
   在模型中,可以直接使用超级对象中的属性
   文件名,全小写
   类名字首字母大写
   建议使用_modle作为后缀,防止和控制器类名冲突
  
  
   url相关函数
   $this->load->helper(‘url’);
   //可以根据需要配置自动加载
   //application/config/autoload.php
   //$autoload[‘helper’]=array(‘url’);
   site_url(‘控制器/方法’)
   base_url()
  
路由
 
application/config/routes.php
//默认控制器
$router[‘default_controller’]=’welcome’;
//http://127.0.0.1/ci/index.php/news/20148/15.html
$route[‘news/[\d]{6}/([\d]+)\.html’]=’article/shoe/$1′;
隐藏入口文件
开启apache的rewite模块,在httpd.conf文件中
LoadModule rewrite_module modules/mod_rewrite.so
重启apache
在入口文件同级目录中放入.htaccess文件
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]     
</IfModule>

分页
        $this->load->library(‘pagination’);//装载类文件
        $this->load->helper(‘url’); //加载url库
        $page_sise = 5;
        $config[‘base_url’] = base_url(‘user/showlist’); //文件路径
        $config[‘total_rows’] = $this->db->count_all_results(‘yyx_posts’);
        ; //总共条数
        $config[‘per_page’] = $page_sise; //每页显示条数
        $config[‘use_page_numbers’] = TRUE;
        $config[‘full_tag_open’] = ‘<p>’;
        $config[‘full_tag_close’] = ‘</p>’;

        $this->pagination->initialize($config);
        $offset = intval($this->uri->segment(3));
        $re = $this->db->get(‘yyx_posts’, $page_sise, $offset);
        //var_dump($re);
        $data[‘showlist’] = $re;
        $this->load->view(‘user/showlist’, $data);
       
文件上传

1.手动创建好上传目录

具体看参考手册,很详细

session
   生成一个随机不重复的字符串作为加密用的key  //   //echo md5(uniqid());exit;
   //保存在application/config/config.php
   //$config[‘encryption_key’]=”;

    public function login() {
        $this->load->library(‘session’);
        $user = array(‘id’ => 1, ‘name’ => ‘admin’);
        $this->session->set_userdata(‘user’, $user);
        //一次性的数据,只能读取一次
        $this->session->set_flashdata(‘test’, ‘123456789’);
    }

    public function show_session() {
        //   echo md5(uniqid());
        $this->load->library(‘session’);
        //取ci session中的数据
        $u = $this->session->userdata(‘user’);
        var_dump($u);
        $t = $this->session->flashdata(‘test’); //只能区一次
        echo $t;
    }
   
验证码

  public function yzm() {
        $this->load->helper(‘url’);
        $this->load->helper(‘captcha’);
        $vals = array(
            //  ‘word’ => ‘Random word’,
            ‘img_path’ => ‘./captcha/’,
            ‘img_url’ => base_url() . ‘/captcha/’,
            //       ‘font_path’ => ‘./path/to/fonts/texb.ttf’,
            ‘img_width’ => ’80’,
            ‘img_height’ => 25,
            ‘expiration’ => 7200
        );

        $cap = create_captcha($vals);
        //echo $cap[‘image’];
        $this->load->view(‘user/showyzm’, array(‘cap’ => $cap[‘image’]));
        session_start();
        $r = $_SESSION[‘cap’] = $cap[‘word’];
        echo $r;
    }
   
表单验证

    public function add_user() {
        $this->load->helper(‘url’);
        $this->load->library(‘form_validation’);
        $this->form_validation->set_rules(‘username’, ‘用户名’, ‘required’);
        //$this->form_validation->set_rules(’email’, ‘邮箱’, ‘required’);
        $this->form_validation->set_rules(’email’, ‘邮箱’, ‘required|valid_email|is_unique[users.email]’);
        $bool = $this->form_validation->run();
        if ($bool) {
            echo ‘OK’;
        } else {
            // $this->load->view(‘formsuccess’);
            // echo ‘OK’;
            $this->load->view(‘user/add_user’);
        }
    }
   
///////////////   
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>表单测试</title>
        </head>
        <body>
            <form method=”post” action=”<?php echo site_url(‘user/add_user’) ?>” >
                名字:<input type=”text” name=”username” value=”<?php echo set_value(‘username’)?>”/>
                 <?php echo form_error(‘username’,'<span>’,'</span>’) ;?><br/>
                邮箱:<input type=”text” name=”email” value=”<?php echo set_value(’email’)?>” />
                <?php echo form_error(’email’,'<span>’,'</span>’) ;?><br/>
                <input type=”submit” value=”submit” />
            </form>
        </body>
</html>

顶一下 1 踩一下 0

你可能对以下内容感兴趣!

  1. win7下配置nginx+php+mysql开发环...
  2. netbeans打开文件中文乱码
  3. 在windows7下配置PHP+Apache+My...
  4. Xammp phpmyadmin连接错误
  5. 在ubnutu 下安装xampp php+mysq...
  6. 为WP主题添加”网页加载中”的特效
  7. WordPress 文字移动特效
  8. 利用jquery实现图片显隐特效

2 个评论 “CodeIgniter(CI)学习笔记整理

发表回复

*

w_0002.gif w_0009.gif w_0007.gif w_0011.gif w_0005.gif w_0008.gif w_0010.gif w_0003.gif w_0012.gif w_0001.gif w_0006.gif