RSS
  • 首页
  • 关于

CodeIgniter 分类下的文章

教程:如何使用CodeIgniter来更新Twitter

十月 14, 2009 by admin | 0 Comment »

这是一篇原创译文,转载请注明出处。
原文作者Drazen Mokic,你可以在 这里 看到原文。

在这个教程里面我们将使用CodeIgniter,通过Twitter API来更新我们的twitter状态。我建议大家一步一步的学习,而不要走马观花式的浏览教程。让我们开始深入学习吧!

教程细节
程序:CodeIgniter框架
版本:1.7.1
难度:高级
预计完成时间:30分钟

1.配置CodeIgniter

首先我们需要对CI的默认配置进行修改。打开 system/application/config/autoload.php 文件,找到下面这行

$autoload['libraries'] = array('');

修改为

$autoload['libraries'] = array('database');

这样就可以自动加载数据库了。接下来,打开 database.php 并修改其中的数据库连接设置-你的数据库名、用户名以及密码。我们使用的名称是 ci_twitter_api。
现在打开 config.php,并修改 base_url 为你的CI目录路径。我使用的目录叫做 twitter_api,我的 system目录就保存在那个位置,因此我的 base_url 会是

$config['base_url']	= "http://localhost/ci/twitter_api";

2.填充数据库

因为我们将要用到数据库,所以我们需要填充一些数据。打开 phpMyAdmin 或者其它你喜欢的数据库管理工具,创建一个新的数据库,命名为 ci_twitter_api。现在我们将要使用下面的SQL查询语句来创建一个表,但请注意,使用你自己的twitter用户名和密码。

1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE IF NOT EXISTS `accounts` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `username` varchar(120) NOT NULL,
     `password` varchar(32) NOT NULL,
     `active` int(11) NOT NULL,
     `last_message` varchar(140) NOT NULL,
     PRIMARY KEY (`id`)
   ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
 
   INSERT INTO `accounts` (`id`, `username`, `password`, `active`, `last_message`) VALUES
   (1, '<strong>YOUR USERNAME</strong>', '<strong>YOUR PASSWORD</strong>', 1, 'No message sent.');
图1

图1

单击右边的 OK 按钮,查询就会被提交。现在你的accounts表的结构应该和下图是类似的:

图2

图2

3.构建模型

转到 system/application/models 下面,新建一个文件并命名为 twitter_model.php。
首先,我们在顶部声明两个全局变量。

1
2
var $accounts_table = 'accounts';
var $update_url = 'http://twitter.com/statuses/update.xml';

因此,$accounts_table 对应的是我们之前所创建的表,$update_url 则是我们用来更新状态的URL。如果Twitter更改了它的更新URL,你只需要修改一次就可以了,不必每次都修改。
现在我们将要创建第一个方法,作用是返回数据库中存储的活跃用户帐户,依据是active字段及其值1。我添加了这一项是因为可能有些人拥有多个twitter账户。

1
2
3
4
5
6
7
class Twitter_model extends Model {
 
    // get the active twitter account from the database, by row active = 1
    function getActiveAccount()
    {
        return $this->db->get_where($this->accounts_table, array('active' => '1'))->row();
    }

我们简单的使用 ActiveRecord 来检索活跃的账户并返回受影响的行。
下一步,我们将要构建主要方法,也就是 update 方法。它将要用到我们的用户名、密码以及我们想要在Twitter上更新的消息。除此之外,它还将对Twitter所返回的 HTTP_CODE 进行解析,以便告诉我们更新是否成功。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// update twitter status and last message on success
function update_status($username, $password, $message)
{
	$ch = curl_init($this->update_url);
 
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
 
	curl_exec($ch);
 
	$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 
	// if we were successfull we need to update our last_message
	if ($httpcode == '200')
	{
		$this->db->where('active', '1');
		$this->db->update($this->accounts_table, array('last_message' => $message));
 
		return TRUE;
	}
 
	else
	{
		return FALSE;
	}
}

乍一看去这段代码有点复杂,但并不是很难理解的。最重要的一点是,我们使用了 cURL 和Twitter进行通信。cURL是一个非常优秀的库,允许我们通过它来发送和接收来自Twitter的HTTP POST数据。
那么,curl_init 初始化一个cURL会话并将URL作为参数接受-在我们这个案例中就是Twitter API所提供的更新URL。
我们通过 curl_setopt 设置了一些选项,这些对于 cURL传输来说是必不可少的。

    CURLOPT_POST: 此项设置为’1′,表示我们将使用 HTTP POST,这与HTML表单中是一样的。
    CURLOPT_POSTFIELDS: 此项接收的是我们想要发送的 POST 数据。在本案例中是 ’status=’ 和我们要发送的消息。我们需要对消息进行 urlencode ,以便使用 ‘%&/” 这类的特殊字符。
    CURLOPT_RETURNTRANSFER: 将此项设置为’1′是非常重要的,因为它将把传输作为字符串返回。这一字符串将告诉我们更新是否成功。
    CURLOPT_USERPWD: 此项的作用是身份验证。它只是以 用户名:密码 这种格式包含我们的twitter帐户信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
curl_exec($ch);
 
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 
// if we were successfull we need to update our last_message
if ($httpcode == '200')
{
	$this->db->where('active', '1');
	$this->db->update($this->accounts_table, array('last_message' => $message));
 
	return TRUE;
}
 
else
{
	return FALSE;
}

在这一部分我们通过 curl_exec() 执行传输并且使用 curl_getinfo(CURLINFO_HTTP_CODE) 来检索返回的HTTP_CODE。这里的HTTP_CODE将告诉我们更新是否成功。代码’200′表示更新成功。你可以在 这里 查看到一份完整的HTTP状态代码列表。
如果我们收到了Twitter所返回的’200′,我们将向数据库发出一条查询语句,用来更新last_message字段,最后我们返回TRUE。如果Twitter没有返回200,我们简单的返回FALSE。
为了完成我们的 twitter_model,我们还将创建最后一个方法,作用是获取我们最后发送的信息。我们之所以需要这个方法是因为我们要在视图中显示最近发送的信息。

1
2
3
4
5
6
7
8
// get the last_message, by row active = 1
function getLastMessage()
{
	$this->db->select('last_message');
	$last_message =  $this->db->get_where($this->accounts_table, array('active' => '1'))->row()->last_message;
 
	return htmlspecialchars($last_message);
}

这个方法很简单。它从我们的活跃帐户所对应的last_message字段检索信息,并经过 htmlspecialchars 转换成HTML实体返回。我们的 twitter_model.php 看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
	class Twitter_model extends Model {
 
	var $accounts_table = 'accounts';
	var $update_url = 'http://twitter.com/statuses/update.xml';
 
	// get the active twitter account from the database, by row active = 1
	function getActiveAccount()
	{
		return $this->db->get_where($this->accounts_table, array('active' => '1'))->row();
	}
 
	// update twitter status and last message on success
	function update_status($username, $password, $message)
	{
		$ch = curl_init($this->update_url);
 
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
 
		curl_exec($ch);
 
		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 
		// if we were successfull we need to update our last_message
		if ($httpcode == '200')
		{
			$this->db->where('active', '1');
			$this->db->update($this->accounts_table, array('last_message' => $message));
 
			return TRUE;
		}
 
		else
		{
			return FALSE;
		}
	}
 
	// get the last_message, by row active = 1
	function getLastMessage()
	{
		$this->db->select('last_message');
		$last_message =  $this->db->get_where($this->accounts_table, array('active' => '1'))->row()->last_message;
 
		return htmlspecialchars($last_message);
	}
}

4.构建控制器
现在转到 system/application/controllers,新建一个文件,命名为 twitter.php。让我们添加几行:

1
2
3
4
5
6
7
8
class Twitter extends Controller {
 
function Twitter()
{
	parent::Controller();
 
	$this->load->model('twitter_model');
}

这是一个简单的CI构造函数,加载我们的 twitter_model。因此整个控制器都是可用的。下面是 index() 方法。

1
2
3
4
5
6
7
8
9
10
function index()
{
	$data['heading'] = 'Hi, send a tweet!';
	$data['last_message'] = $this->twitter_model->getLastMessage();
	$data['active_user'] = $this->twitter_model->getActiveAccount()->username;
 
	$this->load->view('header', $data);
	$this->load->view('index');
	$this->load->view('footer');
}

我们将文本、最近的消息、活跃帐户的用户名等信息传递给 $data 数组。获取最近的消息以及活跃的用户名变得轻而易举,这应该归功于我们的 twitter_model。最后我们加载一些视图(编写完控制器后就会创建它们)。让我们来构建 update 方法吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// updating our status on twitter ( new message )
function update()
{
	if ($this->input->post('submit'))
	{
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');
 
		if ($this->form_validation->run() == FALSE)
		{
			$this->index();
		}
 
		else
		{
			$message = $this->input->post('message');
 
			// get useraccount data
			$account = $this->twitter_model->getActiveAccount();
			$username = $account->username;
			$password = $account->password;
 
			// send a tweet
			if ($this->twitter_model->update_status($username, $password, $message))
			{
				redirect('twitter');
			}
 
			else
			{
				$data['error'] = 'There was an error while updating your status';
 
				$this->load->view('header', $data);
				$this->load->view('error');
				$this->load->view('footer');
			}
		}
	}

这可能又会使你感到迷惑,但我们还是逐步的完成它。

1
2
3
4
5
6
7
8
9
10
11
12
if ($this->input->post('submit'))
	{
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('
<div class="error">', '</div>
');
		$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');
 
		if ($this->form_validation->run() == FALSE)
		{
			$this->index();
		}

我们通过 $this->input->post(’submit’) 检查表单(稍后我们会在主要的视图文件中创建它)是否已被提交。然后,我们加载表单验证类,因为我们希望使用某些输入规则,比如最短5个字符、最多140个字符。此外我们还使用 trim 来过滤掉空格,并将此字段设置为 required(必需),因为我们不需要空的消息。set_rules函数的第一个参数是表单字段的名称,在本案例中是 message (稍后我们会在视图中创建它),第二个参数则是此表单字段的“人性化”的名称,它将被插入到错误信息中(将在视图文件中完成)。
我们调用 $this->form_validation->run() ,此方法返回 TRUE 或者 FALSE。如果我们所设置的某条规则被破坏,它将返回 FALSE 并且调用我们的 index() 方法。而 index() 方法所调用的视图中就会显示错误信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
else
   {
       $message = $this->input->post('message');  
 
       // get useraccount data
       $account = $this->twitter_model->getActiveAccount();
       $username = $account->username;
       $password = $account->password;  
 
       // send a tweet
       if ($this->twitter_model->update_status($username, $password, $message))
       {
           redirect('twitter');
       }  
 
       else
       {
           $data['error'] = 'There was an error while updating your status';  
 
           $this->load->view('header', $data);
           $this->load->view('error');
           $this->load->view('footer');
       }
   }

再次感谢我们的 twitter_model,检索当前的用户名和密码变得轻而易举。当然我们也可以使用 $username = $this->twitter_model->getActiveAccount()->username ,但我觉得对这段教程来说这就更好理解一些。
通过 $this->twitter_model->update_status() 我们调用那个与Twitter进行“通话”的方法。它把我们的用户名、密码以及我们要发送的消息告诉Twitter。如果状态更新成功,我们就会调用URL辅助函数中的 redirect() 进行重定向。
如果出了错,我们设置一条错误消息并加载几个视图文件(下一步会创建它们)。现在控制器看上去是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Twitter extends Controller {  
 
function Twitter()
{
    parent::Controller();  
 
    $this->load->model('twitter_model');
}  
 
function index()
{
    $data['heading'] = 'Hi, send a tweet!';
    $data['last_message'] = $this->twitter_model->getLastMessage();
    $data['active_user'] = $this->twitter_model->getActiveAccount()->username;  
 
    $this->load->view('header', $data);
    $this->load->view('index');
    $this->load->view('footer');
}  
 
// updating our status on twitter ( new message )
function update()
{
    if ($this->input->post('submit'))
    {
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('
<div class="error">', '</div>
');
        $this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');  
 
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();
        }  
 
        else
        {
            $message = $this->input->post('message');  
 
            // get useraccount data
            $account = $this->twitter_model->getActiveAccount();
            $username = $account->username;
            $password = $account->password;  
 
            // send a tweet
            if ($this->twitter_model->update_status($username, $password, $message))
            {
                redirect('twitter');
            }  
 
            else
            {
                $data['error'] = 'There was an error while updating your status';  
 
                $this->load->view('header', $data);
                $this->load->view('error');
                $this->load->view('footer');
            }
        }
    }  
 
    else
    {
        redirect('twitter');
    }
}

5.创建视图
现在我们就要创建视图文件了。转到 system/application/views 下面,创建如下几个文件:
header.php
footer.php
index.php
error.php

header.php将包含基本的HTML元信息、我们的CSS链接以及主要的div(如#wrapper 和 #main)开启标签。

1
2
3
4
5
6
7
8
9
10
11
12
13
< !DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<link media="screen" rel="Stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css" />  
<title>Using the Twitter API with CodeIgniter</title>  
</link></head>  
 
<body>  
 
<div id="wrapper">  
 
<div id="main">

我们使用 base_url() 来引用我们的CSS文件(下一步会创建它)。
footer.php只是包含了我们的关闭标签。

  </div><!--end main-->  
 
    </div><!--end wrapper--></body></html>

index.php才是最重要的部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<h3>
< ?php echo $heading; ?>
 
    ( account: < ?php echo anchor('http://twitter.com/' . $active_user, $active_user); ?> )</h3>
< ?php echo form_error('message'); ?>  
 
   < ?php echo form_open('twitter/update', array('id' => 'update_form')); ?>
   < ?php echo form_input(array('name' => 'message', 'maxlength' => '140')); ?>
   < ?php echo form_submit('submit', 'update'); ?>
   < ?php echo form_close(); ?>
<div id="last_message">
       <fieldset>
           <legend>Last sent by <strong>< ?php echo $active_user ?></strong></legend>  
 
< ?php echo $last_message; ?>
 
       </fieldset></div>
<!--end last_message-->

这里用到的所有变量都是通过我们的控制器中的 index() 方法传递的。除此之外,我们还使用了表单辅助函数来创建一个简单的HTML表单。记住,我告诉过你,这里是进行错误处理的地方;form_error(‘message’) 就是完成这一工作的魔法师。
在表单下面,显示的是当前活跃用户所发送的最后一则消息。
最后,error.php作为一个自定义的错误文件,万一出现更新不成功的情况就可以用得上。

1
2
<h3>< ?php echo $error; ?></h3>
< ?php echo anchor('twitter', 'Go back and try again'); ?>

6.添加一些CSS
为了使页面更加美观,我们将添加一些CSS。转到 system/ 下面并创建 css目录。在那个目录下创建一个 style.css 文件,然后输入如下的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/* Reset CSS */  
 
html, body, div, span, object, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, address, code, img,
small, strong, dl, dt, dd, ol, ul, li,
fieldset, form, label {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baselinebaseline;
    background: transparent;
}  
 
body {
    line-height: 1.5;
    font-family:Arial, sans-serif;
    margin:0;
}
ol, ul, li {
    list-style: none;
    list-style-type:none;
}  
 
.clear { clear:both; }  
 
/* DEFAULTS */  
 
h3 {
    color:#35CCFF;
    font-size:20px;
}  
 
/* CUSTOM */  
 
#wrapper {
    width:900px;
    margin:0 auto;
}  
 
/* main */  
 
#main {
    margin-top:50px;
}  
 
#main h3 span {
    font-size:14px;
    color:#cccccc;
}  
 
#main h3 a {
    color:#cccccc;
}  
 
/* form */  
 
#update_form input {
    width:888px;
    padding:5px;
    border:1px solid #d3d3d3;
    display:block;
}  
 
#update_form input[type="submit"] {
    width:auto;
    margin-top:10px;
    background-color:#000000;;
    border:none;
    color:white;
    font-size:12px;
    font-weight:bold;
    cursor:pointer;
    padding:3px;
}  
 
div.error {
    display:block;
    background-color:#FB8A8A;
    border:1px solid #FF3B3B;
    padding:5px;
    color:#ffffff;
    width:50%;
    margin-bottom:30px;
    font-weight:bold;
    margin:0 auto 10px auto;
    text-align:center;
}  
 
/* last message */  
 
#last_message fieldset {
    border:1px dashed #d3d3d3;
    padding:5px;
    margin-top:30px;
}  
 
#last_message fieldset p {
    padding:5px;
    font-size:18px;
    font-weight:normal;
}  
 
#last_message legend span {
    font-size:12px;
}

我使用了 Eric Meyers 的CSS重置方法,这样可以消除不同浏览器之间的差异。你的应用程序看上去应该像下图这样。

图3

图3

大结局

现在让我们来测试一下新编写的应用程序。我们将输入一条信息并单击 update 按钮!

图4

图4

更新完成后就会显示:

图5

图5

让我们看看Twitter:)

图6

图6

如果我们试图发送一则空消息,破坏了表单验证规则:

图7

图7

结论

我真心希望这对你学习CodeIgniter和如何使用优秀的Twitter API有所帮助!你遇到难题了么? 如果有,请告诉我们!


译者后记

由于众所周知的某原因,如果不使用代理,我们无法在国内访问到Twitter主站,甚至包括其API。这样的话如果使用Twitter官方的API就会导致更新失败。没有关系,我们可以使用第三方的API来完成这个工作。
打开 twitter_model.php ,找到这一行:

var $update_url = 'http://twitter.com/statuses/update.xml';

修改为

var $update_url = 'http://nest.onedd.net/api/statuses/update.xml';

这样就可以了。下面是我的测试结果:

我的测试结果1

我的测试结果1

下面是Twitter主站上看到的结果:

Twitter主站上的测试结果

Twitter主站上的测试结果


CodeIgniter | Tags: API, CodeIgniter, Twitter


CodeIgniter 中文用户指南 版本 1.7.2 CHM版发布(支持索引和搜索)

十月 12, 2009 by admin | 0 Comment »

上个月制作了CodeIgniter 1.7.2中文手册的CHM版,但由于制作工具的原因,生成的索引和搜索结果出现了乱码,非常无奈,只好取消了CHM文件的索引和搜索功能。
最近经过仔细研究后才发现,原始的HTML文件使用的是UTF-8编码,这是造成乱码的根本原因所在。于是用编码转换工具将所有HTML文件的编码转换为GB2312,再用QuickCHM编译生成CHM文件,完美地解决了搜索和索引的乱码问题。

CHM版截图

CHM版截图

单击此处立即下载


CodeIgniter | Tags: CHM, CodeIgniter


CodeIgniter发布1.7.2版

九月 12, 2009 by admin | 0 Comment »

CodeIgniter 发布 1.7.2 版

EllisLab 发布了 CodeIgniter 1.7.2。有什么新内容?主要的更改如下:

兼容 PHP 5.3.0。
新增购物车类库。
改善表单辅助函数。
在公共函数中新增 is_php(),让 PHP 版本比较更方便。
修改 show_error() 以便发送 HTTP 服务器响应码,并且所有内部错误提示都会发送合适的状态码。
修复了很多 BUG。
1.7.2 版已经在 subversion 中存在了很长一段时间了,并且已经于 7 月下旬兼容于 PHP 5.3.0,不过可以理解的是许多用户并没有使用那个开发中的版本。虽然我也希望能有时间为这个版本多增加一些“大改动”的项目,并把版本号变为 1.8,但时间不等人。我们的许多用户都在 Mac 上开发,但 OS X“雪豹”中的 PHP 是 5.3.0,所以与其让用户继续等待不如先推出这个稳定版–毕竟已经 7 个月没有更新了。虽然如此,也还是有一些惊喜和可喜的变化。敬请享用!

以上内容转自http://codeigniter.org.cn/blog。

详细的Change Log:

版本 1.7.2
发布日期:2009年9月11日
SVN 版本: 1737

Libraries
Added a new Cart Class.
Added the ability to pass $config['file_name'] for the File Uploading Class and rename the uploaded file.
Changed order of listed user-agents so Safari would more accurately report itself. (#6844)
Database
Switched from using gettype() in escape() to is_* methods, since future PHP versions might change its output.
Updated all database drivers to handle arrays in escape_str()
Added escape_like_str() method for escaping strings to be used in LIKE conditions
Updated Active Record to utilize the new LIKE escaping mechanism.
Added reconnect() method to DB drivers to try to keep alive / reestablish a connection after a long idle.
Modified MSSQL driver to use mssql_get_last_message() for error messages.
Helpers
Added form_multiselect() to the Form helper.
Modified form_hidden() in the Form helper to accept multi-dimensional arrays.
Modified form_prep() in the Form helper to keep track of prepped fields to avoid multiple prep/mutation from subsequent calls which can occur when using Form Validation and form helper functions to output form fields.
Modified directory_map() in the Directory helper to allow the inclusion of hidden files, and to return FALSE on failure to read directory.
Modified the Smiley helper to work with multiple fields and insert the smiley at the last known cursor position.
General
Compatible with PHP 5.3.0
Modified show_error() to allow sending of HTTP server response codes.
Modified show_404() to send 404 status code, removing non-CGI compatible header() statement from error_404.php template.
Added set_status_header() to the Common functions to allow use when the Output class is unavailable. Common functions to facilitate PHP version comparisons.
Added is_php() to
Added 2 CodeIgniter “cheatsheets” (thanks to DesignFellow.com for this contribution).
1.7.2 修复的 BUG
Fixed assorted user guide typos or examples (#6743, #7214, #7516, #7287, #7852, #8224, #8324, #8349).
Fixed a bug in the Form Validation library where multiple callbacks weren’t working (#6110)
doctype helper default value was missing a “1″.
Fixed a bug in the language class when outputting an error for an unfound file.
Fixed a bug in the Calendar library where the shortname was output for “May”.
Fixed a bug with ORIG_PATH_INFO that was allowing URIs of just a slash through.
Fixed a fatal error in the Oracle and ODBC drivers (#6752)
Fixed a bug where xml_from_result() was checking for a nonexistent method.
Fixed a bug where Database Forge’s add_column and modify_column were not looping through when sent multiple fields.
Fixed a bug where the File Helper was using ‘/’ instead of the DIRECTORY_SEPARATOR constant.
Fixed a bug to prevent PHP errors when attempting to use sendmail on servers that have manually disabled the PHP popen() function.
Fixed a bug that would cause PHP errors in XML-RPC data if the PHP data type did not match the specified XML-RPC type.
Fixed a bug in the XML-RPC class with parsing dateTime.iso8601 data types.
Fixed a case sensitive string replacement in xss_clean()
Fixed a bug in form_textarea() where form data was not prepped correctly.
Fixed a bug in form_prep() causing it to not preserve entities in the user’s original input when called back into a form element
Fixed a bug in _protect_identifiers() where the swap prefix ($swap_pre) was not being observed.
Fixed a bug where the 400 status header sent with the ‘disallowed URI characters’ was not compatible with CGI environments.
Fixed a bug in the typography class where heading tags could have paragraph tags inserted when using auto_typography().
下载1.7.2版:
http://codeigniter.org.cn/downloads


CodeIgniter | Tags: CodeIgniter


[译文]在NetBeans IDE中增加CodeIgniter代码提示

八月 28, 2009 by admin | 0 Comment »

本文原文来自:

http://www.mybelovedphp.com/2009/01/23/netbeans-revisited-code-completion-for-code-igniter/

根据实际情况删减了少量内容,并增加了配图。在NetBeans 6.7.1简体中文版下面测试通过。转载此译文请注明出处。

    对于那些你喜欢的软件,一旦你开始使用它,你就会感觉它就像是为你度身定制的一样。每天你都会一点一点地发现它那隐藏的潜力。这就是开源的好处,还有很多潜在的能力等待我们去发现。大多数商业软件在它们的宣传手册上就已经列出了它们的特性,而最终你开始使用它们的时候你会非常失望。
    NetBeans 6.5是一款好软件,它提供了现成的代码完成和验证功能,支持PHP/HTML/CSS/JavaScript以及jQuery、MooTools等等。
    CodeIgniter是一个PHP快速开发框架,是一个灵活的类MVC系统。NetBeans为CI原生的ActiveRecord类、扩展库和辅助函数提供代码完成功能,帮助你简单地开发CodeIgniter程序。
    你必须先设置好它,下面我们会解释详细步骤:
    如果你将system目录移出了NetBeans项目中包含有application目录的源文件目录(建立多个站点时可能会这么做),那么这一步就是必不可少的。将CodeIgniter的system目录添加到NetBeans的全局包含目录:
选择“工具”>“选项”>“PHP”>“添加文件夹”

译者配图1 添加全局包含目录

译者配图1 添加全局包含目录

这样就可以启用辅助函数的代码完成功能,但是对ActiveRecord或者数据库类的函数不起作用。

$this-&gt;db-&gt;...

因此,必须将下面内容添加到控制器中:

/**
* @property CI_Loader $load
* @property CI_Form_validation $form_validation
* @property CI_Input $input
* @property CI_Email $email
* @property CI_DB_active_record $db
* @property CI_DB_forge $dbforge
*/
class Stylist extends Controller

现在你可以输入

$this-&gt;db-&gt;...

或者

$this-&gt;dbforge-&gt;...

你就会看到代码提示了。Wow!
为了进一步简化,请选择“工具”>“选项”>“编辑器”>“代码模板”:
1.
1.“新建” ->“缩写”:

Db

2.“扩展文本”:

$this-&gt;db-&gt;

2.
1. “新建” ->“缩写”:

`codei`

2.扩展文本:

/**
* @property CI_Loader $load
* @property CI_Form_validation $form_validation
* @property CI_Input $input
* @property CI_Email $email
* @property CI_DB_active_record $db
* @property CI_DB_forge $dbforge
*/

现在你就可以在NetBeans中输入’codei’+Tab或者’db’+Tab,就等同于

$this-&gt;db-&gt;

这样很酷,不是吗?

在前段时间的一篇文章里我展示了一种在NetBeans中支持对CodeIgniter框架进行代码完成的方法。… …也许最简单的方式是在CodeIgniter的application及system目录之外的某个路径下创建一个文件,可以命名为 netbeans_ci_code_completion.php,或者别的任何名字都可以,往文件里写入以下内容:

&lt; ?php
/**
* @property CI_Loader $load
* @property CI_Form_validation $form_validation
* @property CI_Input $input
* @property CI_Email $email
* @property CI_DB_active_record $db
* @property CI_DB_forge $dbforge
* @property CI_Table $table
* @property CI_Session $session
* @property CI_FTP $ftp
* ....
 */
Class Controller {
}
?&gt;

文件名可以随意,但是扩展名必须是 .php,因为这是给NetBeans而不是CI看的。你可以把它保存到一个名叫temp的目录下,或者也可以保存到.nbproject目录(NetBeans的项目目录)下面,保存到这个目录下的好处是这个目录下的内容不会被同步到服务器上。大多数情况下,我的项目的目录结构是这样的:

/application
/error
/images
/nbproject
/scripts
/styles
index.php
.htaccess
译者配图2 实际效果

译者配图2 实际效果


CodeIgniter, 译文 | Tags: CodeIgniter, NetBeans, 代码提示


CodeIgniter辅助函数 – 大写金额转换

八月 24, 2009 by admin | 0 Comment »

在做开发的时候可能会用到数字金额转大写金额这一功能,因此本人参考网上的一些函数,编了这么一个辅助函数,希望能帮得上大家:
< !-more->

&lt; ?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter的人民币金额辅助函数
 * 其中num2rmb函数的作用是用于将阿拉伯数字金额转换为中文大写金额,如将120.50转换为“壹佰贰拾元伍角零分”
 * 请在控制器或视图中通过 $this-&gt;load-&gt;helper('rmb'); 来载入此辅助函数;
 */
if ( ! function_exists('num2rmb')) {
    function num2rmb($Arabic_numbers) {
        $Chinese_numbers=array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖'); //中文大写数字
        //$oldval=$Arabic_numbers; <a href="http://www.yinzhili.com/2009/08/codeigniter-amount-in-words-helper.html#more-63" class="more-link">Read the rest of this entry &raquo;</a>

CodeIgniter | Tags: CodeIgniter, 大写


在CodeIgniter中使用pChart

八月 16, 2009 by admin | 0 Comment »

pChart是一个免费的PHP图表生成库,可以生成多种图表如饼图或者柱状图等等,需要GD库的支持。下面我来简单讲讲如何在CI中方便地使用它。

首先我们要下载pChart。访问http://pchart.sourceforge.net/download.php 就可以下载到最新版的pChart,目前最新的版本是1.27。解压下载到的文件,我们要用到的只是其中的pChart文件夹,里面有pChart.class、pCache.class和pData.class这三个文件。我们把pChart文件夹复制到 application/libraries/ 下面。

然后要准备字体,因为我们做报表很可能要输出中文,所以必须使用一种中文字体,至于选什么字体就看你的喜好了(如果是商业用途的话请注意字体的版权以免引起版权纠纷),把中文字体的ttf文件复制到 application/libraries/pChart 下面即可。

通过库的形式来使用pChart,因此在 application/libraries/ 下面创建一个文件,命名为 Chart.php,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
< ?php
class Chart {
    function Chart() {
        include(APPPATH."libraries/pChart/pData.class");
        include(APPPATH."libraries/pChart/pChart.class");
    }
    function draw_line_graph($params) {
        $DataSet = new pData;
        $DataSet->AddPoint($params['data'],"Serie1");  //需要显示的数据
        $DataSet->AddPoint($params['date'],"Serie2"); //横坐标的数据
        $DataSet->AddSerie("Serie1");
        $DataSet->SetAbsciseLabelSerie("Serie2");
        $DataSet->SetSerieName("订单总金额","Serie1");
        $DataSet->SetYAxisName("RMB"); //纵坐标上显示的文字
        $DataSet->SetXAxisName('横坐标:日期'); //横坐标上显示的文字
        $DataSet->SetXAxisFormat("date"); //横坐标的数据类型
 
        $Test = new pChart($params['height'],$params['width']); //图表文件的高度和宽度
        $Test->setDateFormat($params['date_format']); //横坐标显示的日期格式
        $Test->setColorPalette(0,255,0,0);
 
        $Test->setFontProperties(APPPATH."libraries/pChart/FZLTXIHK.ttf",12); //设置使用的字体及字号
        $Test->setGraphArea(60,60,$params['x_area'],$params['y_area']); //图形区域的高度和宽度
        $Test->drawGraphArea(252,252,252); //线的颜色
        $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
        $Test->drawGrid(4,TRUE,230,230,230,255);
 
        $Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());
        $Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);
        $Test->setFontProperties(APPPATH."libraries/pChart/FZLTXIHK.ttf",8); //设置数据值所用字体及字号
        $Test->writeValues($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie1"); //输出每个点的数据值
 
        $Test->setFontProperties(APPPATH."libraries/pChart/FZLTXIHK.ttf",11); //设置使用的字体及字号
        $Test->drawLegend(75,65,$DataSet->GetDataDescription(),255,255,255);
 
        $Test->setFontProperties(APPPATH."libraries/pChart/FZLTXIHK.ttf",12); //设置使用的字体及字号
        $Test->drawTitle(60,22,$params['title'],50,50,50,585);
 
        $imagefile='public/temp/'.$params['filename'].'.png'; //设置生成文件的保存路径
        $Test->Render($imagefile);   //生成文件
 
      return $imagefile;  //返回文件名
    }
}

然后控制器中这样调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function test(){
     $this->load->library('chart'); //载入pChart库
 
   $params['data']=array(100,200,150,600,230,150,510); //要显示的数据
   for($i=0;$i&lt;7;$i++){
         $params['date'][$i]=1250217066+$i*86400; //要显示的日期,注意这里是Unix时间戳,pChart会自动传换成你要的格式
  }
    $params['title']='销售报表'; //图片标题
   $params['date_format']='m月j日';//设置日期格式
   $params['filename']='test_image';  //文件名     
   $params['height']=600; //高度
   $params['width']=300; //宽度
   $params['x_area']=560; //图形区域高度
   $params['y_area']=280; //图形区域宽度
   $data['chart_image']=$this->chart->draw_line_graph($params);//生成图片
   $data['baseurl']=site_url();
    $this->load->view('test_view.html',$data);
}

视图中输出就很简单了:

1
2
3
4
5
6
<html>
<head><title></title></head>
<body>
<img src="<?php echo $baseurl.$chart_image;?/>" />
</body>
</html>

关于pChart的更多用法,请参考它的在线文档:

http://pchart.sourceforge.net/documentation.php


CodeIgniter | Tags: CodeIgniter, pChart


CodeIgniter辅助函数-敏感词过滤

八月 5, 2009 by admin | 0 Comment »

我们都知道有些敏感的词汇是不适合出现在互联网上的,特别是在有用户留言或发帖的一些站点,如博客或者论坛,如果出现了敏感词,那将是一件十分麻烦的事情。所以如果你打算用CodeIgniter开发这类站点,对用户输入的内容就必须加以过滤,因此本人就编写了这样一个辅助函数,这可是真真正正有“中国特色”的辅助函数。原理很简单,本质上说就是替换字符串,并没有国内一些大型论坛那么智能,如果需要更智能的过滤方法,就需要用正则表达式对用户的输入内容进行分析了,当然这里并没有用到。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
< ?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter的关键字过滤函数
 * 用于在字符串中过滤一些敏感关键字
 * 请在控制器或视图中通过 $this-&gt;load-&gt;helper('filter'); 来载入此辅助函数;
 *
 *
 */
 
if ( ! function_exists('clean')) {
    function clean($string) {
        //请自行增减此数组内容,以达到最好过滤效果
        $keywords= array(
            'shit' => 's**t',
            'Shit' => 'S**t',
            'twat' => 't**t',            
            '他妈的' => 'TMD',
            '狗日的' => '狗X的',
            'X你妈' => '草泥马',
            '躲猫猫' => '朵猫猫',
            '70码' => '欺实马',
            'Yamete' => '雅蔑蝶',
            'fuck you' => '法克鱿',
            '叉腰肌' => '猹妖鸡',            
            '90后' => '九岭猴',
            '傻B' => '傻X'            
           );
        return strtr($string, $keywords);
    }
}
 
/* filter_helper.php 文件结束 */
/* 本文件的位置应该是: ./system/application/helpers/filter_helper.php */

CodeIgniter | Tags: CodeIgniter, helper, 过滤


CodeIgniter自定义扩展-XML库

八月 3, 2009 by admin | 0 Comment »

这是用于CodeIgniter的XML扩展库,用来解析XML文档,修改里面的结点以及获取结点内容。原版来自:http://codeigniter.com/wiki/Xml_Library/,当然原版只有基本的解析XML功能,我对这个类进行了一点扩展,可以满足通常情况下的需要了。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
< ?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
 
/**
 * 用于CodeIgniter的XML解析库
 *
 * 提供XML文档哦解析和修改结点值的功能。
 * 注意:此库仅适用于PHP5。
 * @author: (原作者)Woody Gilk   (注释及扩展): yinzhili
 * @version 1.0
 *
 * 许可: http://creativecommons.org/licenses/by-sa/2.5/
 * URL: http://codeigniter.com/wiki/Xml_Library/
 *
 * 说明: 请通过以下方式来加载这个类库:$this->load->library('xml');
 *
 */
 
class Xml {
    function Xml () {
    }
 
    private $document;
    private $filename;
 
    public function load($file) {
    /**
     * 载入需要解析的XML文件
     *
     * $file:需解析的XML文件及其路径(请省略 .xml 扩展名,此处路径为相对于 APPPATH 的路径)
     * 例如:test.xml 文件保存在 application/config/test.xml 这个位置,那么 $file='config/test.xml' 。
     * 请确保路径正确,否则无法解析。
     */
        $bad  = array('|//+|', '|\.\./|');
        $good = array('/', '');
        $file = APPPATH.preg_replace ($bad, $good, $file);//生成需要解析的.xml文件的完整路径
 
        if (! file_exists ($file)) {
            return false; //如果在指定位置找不到要解析的.xml文件,返回false
        }
 
        $this->document = file_get_contents($file); //将整个文件读入字符串
        $this->filename = $file;
 
        return true;
    }  /* load函数结束 */
 
    public function parse() {
    /***
     * @public
     * 对一个XML文档进行解析,结果存入数组
     */
        $xml = $this->document;
        if ($xml == '') {
            return false; //如果XML内容为空,则返回false
        }
 
        $doc = new DOMDocument ();
        $doc->preserveWhiteSpace = false;
        if ($doc->loadXML ($xml)) {
            $array = $this->flatten_node ($doc);
            if (count ($array) > 0) {
                return $array;
            }
        }
 
        return false;
    } /* parse函数结束 */
 
    private function flatten_node($node) {
    /***
     * @private(私有函数)
     * 将XML文档解析为一个数组
     */
 
        $array = array();
 
        foreach ($node->childNodes as $child) {
            if ($child->hasChildNodes ()) {
                if ($node->firstChild->nodeName == $node->lastChild->nodeName && $node->childNodes->length > 1) {
                    $array[$child->nodeName][] = $this->flatten_node ($child);
                }
                else {
                    $array[$child->nodeName][] = $this->flatten_node($child);
 
                    if ($child->hasAttributes ()) {
                        $index = count($array[$child->nodeName])-1;
                        $attrs =& $array[$child->nodeName][$index]['__attrs'];
                        foreach ($child->attributes as $attribute) {
                            $attrs[$attribute->name] = $attribute->value;
                        }
                    }
                }
            }
            else {
                return $child->nodeValue;
            }
        }
        return $array;
    }
    /*  node_to_array函数结束 */
 
 
    public function set($file,$node,$new_value) {
    /**
     * @public(公有函数)
     * 修改XML文档中某个节点的值
     * 各个参数含义如下: $file为要修改的XML文件,$node为要修改其值的结点名称,$new_value为新值
     * 如果修改成功,函数将返回true
     */
        $bad  = array('|//+|', '|\.\./|');
        $good = array('/', '');
        $file = APPPATH.preg_replace ($bad, $good, $file);//生成需要解析的.xml文件的完整路径
 
        if (! file_exists ($file)) {
            return false; //如果在指定位置找不到要解析的.xml文件,返回false
        }
        else {
            $xml = new DOMDocument(); //实例化DOMDocument对象
            $xml->load($file); //加载XML文件
            if($xml->getElementsByTagName($node)!=null) { //如果XML文件中存在相应结点
                foreach($xml->getElementsByTagName($node) as $list) {
                    $list->nodeValue=$new_value;//将结点的值修改为参数中给出的新值
                    $xml->save($file);//保存修改之后的文件
                    return true; //返回true
                }
            }
            else {
                return false; //如果找不到参数中给出的结点,则返回false;
            }
        }
    }
    /* update函数结束 */
 
 
    public function get($file,$node) {
    /**
     * @public(公有函数)
     * 获取XML文档中某个节点的值
     * 各个参数含义如下: $file为要修改的XML文件,$node为要获取其值的结点名称
     * 如果修改成功,函数将返回获取结果
     */
        $bad  = array('|//+|', '|\.\./|');
        $good = array('/', '');
        $file = APPPATH.preg_replace ($bad, $good, $file);//生成需要解析的.xml文件的完整路径
 
        if (! file_exists ($file)) {
            return false; //如果在指定位置找不到要解析的.xml文件,返回false
        }
        else {
            $xml = new DOMDocument(); //实例化DOMDocument对象
            $xml->load($file); //加载XML文件
            if($xml->getElementsByTagName($node)!=null) { //如果XML文件中存在相应结点
                foreach($xml->getElementsByTagName($node) as $list) {
                    return $list->nodeValue;//返回结果
                }
            }
            else {
                return false; //如果找不到参数中给出的结点,则返回false;
            }
        }
    }
 
}
 
/*
 * XML.php 文件结束。此文件的正确保存路径应该是 application/libraries/XML.php
 * 请注意: 此处省略 ?> 闭合标签是为了避免出现错误,并非遗漏。
 */

请将此文件保存在此路径下: application/libraries/XML.php ,然后通过

1
$this->load->library('xml');

来加载这个扩展就可以了。


CodeIgniter | Tags: CodeIgniter, XML


IT狂人的博客

  • 声明

    本博文章及相关作品(包括但不限于文字、图片),除特别说明为转载外,均属本人原创,依据《国家知识产权法》、《著作权法》和《信息网络传播权保护条例》,原创知识产权、版权均为本人所有,本人享有著作权,并受法律保护。

    文章欢迎转载,但请事先与本人联系:email
    未经本人许可,任何人不得转载或使用整体或任何部分的内容。未尽事宜,依据相关法律法规处理。

  • 分类目录

    • ASP .Net (1)
    • CodeIgniter (8)
    • PHP (8)
    • Web (5)
    • 未分类 (1)
    • 杂谈 (4)
    • 译文 (7)
    • 音乐&电影 (1)
  • 文章索引模板

    • 2010年七月 (5)
    • 2010年五月 (1)
    • 2010年四月 (1)
    • 2010年三月 (2)
    • 2010年二月 (1)
    • 2010年一月 (2)
    • 2009年十二月 (1)
    • 2009年十月 (2)
    • 2009年九月 (3)
    • 2009年八月 (10)
  • 标签

    AJAX API AVC CakePHP CHM CodeIgniter CURD Django DroidSansFallback eaccelerator footer Framework Fran Healy Git helper IT Kohana MVC MVP MYSQL NetBeans Oasis ORM pChart pdf PHP phpMyAdmin Ruby tcpdf techified time Travis Twitter Web windows Wordpress XML Zend 传记 外链 大写 孔乙己 框架 盗链 过滤
  •  

    2010年七月
    一 二 三 四 五 六 日
    « 五    
     1234
    567891011
    12131415161718
    19202122232425
    262728293031  
  • Playlist


  • 最近评论

    • cnenc 在 使用PHP的Glob()函数来遍历文件夹 上的评论
    • TCPDF开源项目 - PDF - php开源项目 - php免费pdf生成软件 - php开源软件 - TCPDF - 开源网 在 使用TCPDF输出完美的中文PDF文档 上的评论
    • 匿名 在 在Windows下编译适用于PHP 5.2.12及5.2.13的eAccelerator.dll(附下载) 上的评论
    • 笑话大王 在 使用TCPDF输出完美的中文PDF文档 上的评论
    • admin 在 在Windows下编译适用于PHP 5.2.12及5.2.13的eAccelerator.dll(附下载) 上的评论
  • 链接

    • cnBeta.COM
    • CodeIgniter 中国
    • jQuery中文社区
    • Lily Allen
    • Mtime时光网
    • W3School
    • 小众软件
    • 破烂熊乐园
    • 韩寒
Copyright © 2010 IT狂人的博客 All Rights Reserved. XHTML CSS THEME by I SOFTWARE REVIEWS