用户
 找回密码
 入住 CI 中国社区
搜索
查看: 14334|回复: 6
收起左侧

[中级] 从头学CodeIgniter和Doctrine 第三天 用户注册【翻译】上

[复制链接]
发表于 2010-1-25 14:17:59 | 显示全部楼层 |阅读模式
本帖最后由 baiyuxiong 于 2010-1-25 14:31 编辑

英文原文:http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-3-user-signup-form翻译:http://baiyuxiong.com/article/123.htm


超过帖子字数限制了,只好发两篇,下篇:
http://codeigniter.org.cn/forums/thread-4633-1-1.html

在这一部分,我们通过以下几步来建立一个用户注册表单。
- 我们用Doctrine建立一个"user" 模型.
- 学习Mutators.
- 用Doctrine创建数据表.
- 从CodeIgniter的url里删除index.php
- 建立注册表单并设计样式
- 学习Helpers、Libraries以及如何扩展他们
- 表单验证和重复检查。


让我们建立一个Doctrine模型

由于我们今天要建立一个用户注册表单,最好从"user"模型开始。我们的模型继承自Doctrine_Record类,代表"user"表中的数据记录
让我们来建一个:
  • 在system/application/models下创建一个user.php文件。
  • 类名为User,要与文件名匹配。
  • 类名首字母要大写,但文件名通常是小写的。(这是CodeIgniter的规定,不是Doctrine的。但我们还是要和它保持一致)。
  • 我们添加一个方法setTableDefinition(),包含字段信息。再添加一个方法setUp(),包含一些附加的选项。
PHP复制代码
 
//system/application/models/user.php
 <?php
class User extends Doctrine_Record {
    public function setTableDefinition() {
        $this->hasColumn('username', 'string', 255, array('unique' => 'true'));
        $this->hasColumn('password', 'string', 255);
        $this->hasColumn('email', 'string', 255, array('unique' => 'true'));
    }
    public function setUp() {
        $this->setTableName('user');
        $this->actAs('Timestampable');
    }
}
复制代码

看起来很简单吧?现在来回顾一下代码。

$this->hasColumn()
结构:
$this->hasColumn($name, $type = null, $length = null, $options = array());
这个函数告诉Doctrine数据表的字段结构。除了$name,其它参数都是可选。支持的类型$type有:Boolean, Integer, Float, Decimal, String, Array, Object, Blob, Clob, Timestamp, Time, Date, Enum, Gzip.
$options通过‘name’ => ‘value’,键值对的形式传递一个数组。我们给两个字段传送了unique选项,意思在他们上建立唯一索引。
在这个上,我们不需要知道太多细节,如果你想了解,请阅读Doctrine的文档。

$this->setTableName()
结构:
$this->setTableName($table_name);
设置模型将要使用的表,可以使用一个与模型完全不同的名称。

$this->actAs()
给模型添加一个行为
我们使用的是Timestampable,它给表添加了2个字段created_at和updated_at,并管理它们。你猜对了,它们跟踪记录创建和更新的时间。
注意:当我们添加这个行为时,并不需要在setTableDefinition函数中指定这两个字段。

添加Mutators

安全起见,我们希望password字段能自动加密,这时就需要Mutators了。
我们修改一下模型
system/application/models/user.php (新代码突出显示)
PHP复制代码
 
<?php
class User extends Doctrine_Record {
    public function setTableDefinition() {
        $this->hasColumn('username', 'string', 255, array('unique' => 'true'));
        $this->hasColumn('password', 'string', 255);
        $this->hasColumn('email', 'string', 255, array('unique' => 'true'));
    }
    public function setUp() {
        $this->setTableName('user');
        $this->actAs('Timestampable');
       $this->hasMutator('password', '_encrypt_password');
    }
        protected function _encrypt_password($value) {
        $salt = '#*seCrEt!@-*%';
        $this->_set('password', md5($salt . $value));
    }
}
复制代码
首先,我们给password字段添加了一个Mutator函数:_encrypt_password。
然后以Model类的内部函数的方式实现它。
注意:为使mutators正常工作,auto_accessor_override选项需要启用。在插件文件doctrine_pi.php里,我们已经做好了。

让Doctrine创建数据表

当Doctrine能为我们创建表的时候,我们为什么要自己手动做呢!
我们使用Doctrine的静态类创建表,像这样:

Doctrine::createTablesFromModels();

我们来写一段简单可重用的代码,可以用它来重复创建数据库。

创建控制器: system/application/controllers/doctrine_tools.php
PHP复制代码
 
<?php
class Doctrine_Tools extends Controller {
    function create_tables() {
        echo 'Reminder: Make sure the tables do not exist already.<br />
        <form action="" method="POST">
        <input type="submit" name="action" value="Create Tables"><br /><br />'
;
        if ($this->input->post('action')) {
           Doctrine::createTablesFromModels();
            echo "Done!";
        }
    }
}
 
复制代码

注意突出显示的那行代码,它简单的读取Doctrine Model类的文件,并在数据库中为它们创建表。
我知道代码有点儿丑,但我们只是在建立初始model的时候暂时用一下这个控制器。

首先确定user表不存在。如果存在,用phpmyadmin删除它。
转到: http://localhost/ci_doctrine/index.php/doctrine_tools/create_tables 并点击按钮.
检查我们的新表.


注意: id字段是自动生成的. 我们在插件文件doctrine_pi.php中已经设置过了:
PHP复制代码
 
// set the default primary key to be named 'id', integer, 4 bytes
Doctrine_Manager::getInstance()->setAttribute(
    Doctrine::ATTR_DEFAULT_IDENTIFIER_OPTIONS,
    array('name' => 'id', 'type' => 'integer', 'length' => 4));
复制代码
现在让我们对CodeIgniter做一些调整。

从CodeIgniter的url中删除index.php

我们希望url能像这样:
http://localhost/ci_doctrine/welcome
而不是这样:
http://localhost/ci_doctrine/index.php/welcome

更短,更干净,更好。
以下几步:
  • web服务器需要开启mod_rewrite。
  • WAMP用户:左键系统托盘-> Apache -> Apache Modules -> rewrite_module,在工程目录“ci_doctrine”下创建文件名为.htaccess的文件。
  • 复制粘贴下面代码:
.htaccess:

TEXT复制代码
 
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /ci_doctrine/index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
    ErrorDocument 404 /ci_doctrine/index.php
</IfModule>
 
复制代码

现在需要告诉CodeIgniter我们要从URL中移除index.php.
编辑: system/application/config.php
PHP复制代码
 
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/

$config['index_page'] = "";
 
复制代码

就是这样!
检测配置是否修改成功, 访问: http://localhost/ci_doctrine/welcome.
你应该能看到欢迎页面.

创建注册表单

写代码前先决定我们要怎么做。
游戏计划

我们需要一个叫signup的控件器,所以注册表单的URL变成:http://localhost/ci_doctrine/signup
我们希望signup控制器自动载入一个叫做signup_form的View。这个View包含表单的html。
表单提交后交给signup控制器的submit方法处理,即:signup/submit.
在那里,我们需要验证用户输入,必要的时候显示错误信息。
最后利用新Doctrine模型,把新用户添加到数据库

“Signup” Controller
  • 创建这个文件: system/application/controllers/signup.php
PHP复制代码
 
<?php
class Signup extends Controller {
    public function __construct() {
        parent::Controller();
    }
    public function index() {
        $this->load->view('signup_form');
    }
}
 
复制代码

分析代码:
  • 首先创建了一个构造函数(__construct)。这个函数每次都是最先被调用。
  • 构造函数是可选的,但我决定创建一个。
  • 在构造函数内,我们总是必须先调用父构造函数(第6行)。
  • 在index(做为控制器的默认方法)方法里,我们载入了一个名称为signup_form的view。

“signup_form” View
  • 创建文件: system/application/views/signup_form.php
HTML复制代码
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Signup Form</title>
</head>
<body>
<div id="signup_form">
    <p class="heading">New User Signup</p>
</div>
</body>
</html>
 
复制代码

现在,它只是一个简单的HTML文件。

  • 访问: http://localhost/ci_doctrine/signup
你应该能看到输出:

HTML复制代码
 
New User Signup

复制代码

CodeIgniter 辅助函数

辅助函数在目录system/helpers下。他们包含一些实用的功能,让我们工作变的更容易。
在这个教程里,我们使用了url和form辅助函数。
可以像这样载入他们:
PHP复制代码
 
$this->load->helper('url');
复制代码


或者一次载入多个辅助函数:
PHP复制代码
 
$this->load->helper(array('form','url'));
复制代码


CodeIgniter 类库

类库与辅助函数很相似,但类库通常是面向对象的。
我们将使用form_validation类库,像这样载入它:
PHP复制代码
 
$this->load->library('form_validation');
复制代码


一旦载入后,就能像这样访问它:
PHP复制代码
 
$this->form_validation->//...
复制代码


把他们添加到控制器

编辑: system/application/controllers/signup.php
PHP复制代码
 
<?php
class Signup extends Controller {
    public function __construct() {
        parent::Controller();
       $this->load->helper(array('form','url'));
        $this->load->library('form_validation');
    }
    public function index() {
        $this->load->view('signup_form');
    }
}
 
复制代码

注意:当你在构造函数内载入辅助函数和类库时,他们在控制器的所有方法中都有效。例如:现在index函数可以使用它们。
注意2:当views载入后,它们也可以使用控制器载入的辅助函数和类库。



接下篇:http://codeigniter.org.cn/forums/thread-4633-1-1.html
 楼主| 发表于 2010-1-25 14:22:59 | 显示全部楼层
编辑器不支持某行代码的突出显示和行号。
大家凑和看吧。

谢谢HEX支持!
发表于 2010-1-25 14:41:21 | 显示全部楼层
呵呵,看来代码高亮还得完善一下~~
发表于 2010-1-25 23:34:32 | 显示全部楼层
支持下楼上的  
你翻译的那套orm的教程 我也想过翻译的

不过当初我想着把它的教程省略一些,因为有一些介绍ci的知识

很开心的看到你翻译这些  继续加油

呵呵 如果有机会的话,希望跟你合作翻译ci的另外一本书籍 《professional codeigniter》这本书前阵子跟个朋友一起翻译了少许内容,由于某些原因终止了,不过想着春节继续翻译的。

不知道楼主是否有兴趣,呵呵 。。

我的qq:174418075
发表于 2010-3-12 14:11:34 | 显示全部楼层
大家的英语水平很高啊。好羡慕啊
发表于 2010-4-9 14:34:43 | 显示全部楼层
本帖最后由 tempa 于 2010-4-9 14:36 编辑

学习一下。
发表于 2010-7-23 10:40:19 | 显示全部楼层
学习,顶

本版积分规则