实验17:PHP ActiveRecord 简化数据库操作

简单实验 飞快学 699浏览

PHP ActiveRecord

关键词:ActiveRecord ORM(Object Relational Mapping)

php-activerecord is an open source ORM library based on the ActiveRecord pattern. It aims to massively simplify the interactions with your database and eliminate the chore of hand written SQL for common operations. Unlike other ORMs, you do not need to use any code generators nor maintain mapping files for your tables. This library was inspired by Ruby on Rails’ implementation and therefore borrows many of its conventions and ideas.

官方网站: http://www.phpactiverecord.org/

下载zip包: http://example.phpsoeasy.com/php-activerecord.zip

KtUQF

jooctrine-doctrine-orm-in-joomla-4-638

创建文件 db_sakila.php,建议将该文件放置在 common 目录下,内容如下:

<?php

require_once 'php-activerecord/ActiveRecord.php';

ActiveRecord\Config::initialize(function($cfg)
{
    $dsn = 'mysql://用户名:密码@localhost/数据库名?charset=utf8';
    $cfg->set_connections(array('development' => $dsn));
});
 
class Film extends ActiveRecord\Model
{
    static $table_name = 'film';
}
?>

创建文件 110.php,应用程序和 common 目录在同一层目录,显示 film 表中序号为1的记录的标题和描述。示例: http://example.phpsoeasy.com/sakila/110.php

<?php
require_once '../common/db-sakila.php';

$film = Film::find(1);
printf("Title: %s<br/>\n", $film->title);
printf("Description: %s<br/>\n", $film->description);
?>

创建文件 111.php,更新 film 表中序号为2的记录的标题和描述。

<?php
require_once '../common/db-sakila.php';
header("Content-type:text/html;charset=utf-8");

$film = Film::find(2);
$film->title = '金手指';
$film->save();
printf("Title: %s<br/>\n", $film->title);
printf("Description: %s<br/>\n", $film->description);
?>
require_once '../common/db-sakila.php';
header("Content-type:text/html;charset=utf-8");

$film = new Film();
$film->title = '金手指';
......
$film->save();

http://www.phpactiverecord.org/projects/main/wiki/Finders