CI框架学习笔记一

CI框架学习笔记一

一、CI框架注意事项

  1. CI框架ControllerModel的php文件名和类名都要大写首字母,但是load的时候全部小写。

  2. 辅助函数,顾名思义,是帮助我们完成特定任务的函数。每个辅助函数文件仅仅是一些函数的集合。例如,URL Helpers 可以帮助我们创建链接,Form Helpers 可以帮助我们创建表单,Text Helpers 提供一系列的格式化输出方式,Cookie Helpers 能帮助我们设置和读取COOKIE, File Helpers 能帮助我们处理文件,等等。

  3. 载入多个辅助函数

    $this->load->helper( array('helper1', 'helper2', 'helper3') );

  4. 控制器中有一个方法,名为 index() 。"index" 方法总是在 URI 的第二段为空时被调用。例如下面的url均可调用index方法。

   http://localhost/blog/

   http://localhost/blog/index.php

   http://localhost/blog/index.php/view

   http://localhost/blog/index.php/view/index

如果你在config/config.php里面的设置了自定义url后缀$config['url_suffix'] = '.html';,那么下面的url也是可以访问的。

http://localhost/blog/index.php/view/index.html

  • 去除链接中的index.php需要配置服务器重写规则。
  1. 如果你打算在你的控制器中使用构造函数,你必须将下面这行代码放在里面:

    parent::__construct();	
    
  2. 通过视图加载方法的第二个参数可以从控制器中动态的向视图传入数据, 这个参数可以是一个数组 或者一个对象 。

二、CI加载静态类库

​ 今天在使用CI框架加载Requests库的时候,报错,由此深入研究了一下,发现报错信息为构造函数为私有函数,看了Requests库的内容,基本都是静态方法,静态类不能实例化,构造函数是私有的。以下几个方面都可以解决这个问题:

解决方法:

  1. 直接将构造函数的private改为public,即可使用
  2. 使用include+全路径
  3. 使用include+常量路径(就是CI自带的路径常量,见下五介绍)

几个定义的常量(PATH结尾的常量表示目录路径,DIR结尾的变量表示目录名):

a. SELF(这里指index.php文件)
b. EXT(deprecated,废弃的,不必关注)
c. BASEPATH(system文件夹的路径)
d. FCPATH(前端控制器的路径)
e. SYSDIR(系统system目录名)
f. APPPATH(应用程序路径)

查看所有定义的常量的方法:

Print_r(get_defined_constants());

  1. 作为辅助函数加载

注意文件名的格式(函数名_helper.php)

  1. 使用类库,以下摘抄自stackoverflow上大神的回答

There is a simple way to use Requests for PHP with Codeigniter.

You may follow these few easy steps.

Step - 1

Unzip latest Requests for PHP zip and copy the contents of the library directory to {codeigniter_directory}/application/third_party/Request-{version} for example you have Requests for PHP 1.6.0 and your CI project is in /usr/sites/www/myciproject then copy the files to /usr/sites/www/myciproject/application/third_party/Requests-1.6.0.

Step - 2

Create a file PHPRequests.php in {codeigniter_directory}/application/libraries with this content

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

require_once APPPATH."/third_party/Requests-1.6.0/Requests.php";
class PHPRequests {
    public function __construct() {
       Requests::register_autoloader();
    }
}

Step - 3

In your controller you can use Requests by loading PHPRequests library we created in previous step.

$this->load->library('PHPRequests');

Like this test function

public function test()
{
    $this->load->library('PHPRequests');
    $response = Requests::get('https://github.com/timeline.json');
    var_dump($response->body);
}

猜你喜欢

转载自www.cnblogs.com/lzhd24/p/9027989.html