fuelphp 模型和数据库
模型在 fuelphp web 框架中扮演着重要的角色。它代表应用程序的业务实体。它们要么由客户提供,要么从后端数据库获取,根据业务规则进行操作并持久化回数据库中。让我们在本章中了解模型以及它们如何与后端系统交互。
创建模型
在 fuelphp 中,模型只是简单的 php 类扩展内置模型类。默认情况下,模型可能以 model_ 为前缀,类似于控制器,应该放在 fuel/app/classes/model/ 文件夹中。让我们创建一个基本的员工模型,并在继续进行时对其进行扩展。
fuel/app/classes/model/employee.php
namespace model;
class model_employee extends \model {
public static function fetchall() {
// code to fetch employee from database
}
}</pre-->
<h2>访问模型</h2>
一旦定义了模型,就可以在任何控制器中自由使用它,只需将其包含在控制器中,如下所示。
use \model\employee;
class controller_employee extends controller {
public function action_index() {
$employees = employee::fetchall();
}
}
<h2>数据库概览</h2>
fuelphp 提供了自己的数据库抽象层来从数据库中获取数据。它提供了基本的和高级的基于 orm 的工具。基本工具包由基于 db、dbutil 和 query_builer 的类组成。高级工具包是 orm。 orm 工具包派生自基础工具包并捆绑为一个单独的包。
<h2>数据库配置</h2>
fuelphp 将数据库设置与主配置文件分开,该文件是 <strong>fuel/app/config/db.php</strong>。它支持为每个环境单独设置。目前,fuelphp 支持 mysql、mysqli 和 pdo 驱动程序。示例设置如下:
return array (
'development' =--> array (
'type' => 'mysqli',
'connection' => array (
'hostname' => 'localhost',
'port' => '3306',
'database' => 'tutorialspoint_fueldb',
'username' => 'root',
'password' => 'password',
'persistent' => false,
'compress' => false,
),
'identifier' => '`',
'table_prefix' => '',
'charset' => 'utf8',
'enable_cache' => true,
'profiling' => false,
'readonly' => false,
),
)
<h2>基于数据库的工具包</h2>
<strong>db 类</strong> 是从应用程序访问数据库的最简单选项。它提供了构建数据库查询、针对目标数据库执行并最终获取结果的选项。 <em>db</em> 类与以下类交互并提供全面的数据库 api。
<ul>
<li><strong>database_connection</strong>-与数据库交互的单例和主类</li>
<li><strong>database_query</strong>-执行 sql 查询和获取结果的基础、具体类</li>
<li><strong>database_query_builder</strong>-构建 sql 查询的基础抽象类</li>
<li><strong>database_query_builder_join</strong>-构建 sql 连接的类</li>
<li><strong>database_query_builder_where</strong>-构建 sql 查询条件的抽象类</li>
<li><strong>database_query_builder_select</strong>-构建 sql 选择查询的具体类</li>
<li><strong>database_query_builder_insert</strong>-构建 sql 插入查询的抽象类</li>
<li><strong>database_query_builder_update</strong>-构建 sql 更新查询的抽象类</li>
<li><strong>database_query_builder_delete</strong>-构建 sql 删除查询的抽象类</li>
</ul>
下图描述了类和类提供的方法之间的关系。
<img src="/public/core/edit/php/../attached/20231217205439_65489.jpg" alt="" border="0" />
<h2>数据库 api</h2>
让我们在本节中学习 db 类中可用的最重要的方法。
<h3>实例</h3>
<ul>
<li><strong>目的</strong>-创建并返回新的 <em>database_connection</em> 实例。</li>
<li><strong>参数</strong>-</li>
<li><strong>$db</strong>-配置文件中定义的数据库连接名称,可选。</li>
<li><strong>返回</strong>-返回<em>database_connection</em> 对象</li>
</ul>
例如
$db = db::instance();
$db = db::instance('test');
<h3>查询</h3>
<ul>
<li><strong>目的</strong>-准备提供的 sql 语句并返回 database_query 对象,该对象可用于插入、更新、删除或从数据库中获取数据。</li>
<li><strong>参数</strong>-</li>
<li><strong>$query</strong>-sql 语句,可能包含占位符;</li>
<li><strong>$type</strong>-sql 类型,可选(db::select、db::insert、db::update 和 db::delete)</li>
<li><strong>返回</strong>-返回<em>database_query</em> 对象</li>
</ul>
例如
$query = db::query('select * from 'employees'');
<h3>last_query</h3>
<ul>
<li><strong>目的</strong>-获取最后执行的查询</li>
<li><strong>参数</strong>-无</li>
<li><strong>returns</strong>-返回最后执行的查询</li>
</ul>
例如
$employees = db::select('select * from 'employee'');
$sql = db::last_query();
<h3>选择</h3>
<ul>
<li><strong>目的</strong>-生成查询的选择部分</li>
<li><strong>参数</strong>-</li>
<li><strong>$columns</strong>-数据库列名列表</li>
<li><strong>返回</strong>-返回 database_query_builder_select 对象</li>
</ul>
例如
$query = db::select(); // select *
$query = db::select('id', 'name'); // select id, name
<h3>select_array (db)</h3>
它与 select 类似,只是我们可以将列作为数组发送。
$query = db::select_array(array('id', 'name')); // select id, name
<h3>插入</h3>
<ul>
<li><strong>目的</strong>-生成查询的插入部分</li>
<li><strong>参数</strong>-</li>
<li><strong>$table_name</strong>-数据库表的名称;</li>
<li><strong>$columns</strong>-表列数组</li>
<li><strong>返回</strong>-返回 database_query_builder_insert 对象</li>
</ul>
例如
$query = db::insert('employee'); // insert into employee
$query = db::insert('employee', array('id', 'name')); // insert into employee (id, name)
<h3>更新</h3>
<ul>
<li><strong>目的</strong>-生成查询的更新部分</li>
<li><strong>参数</strong>-</li>
<li><strong>$table_name</strong>-数据库表名</li>
<li><strong>返回</strong>-返回 database_query_builder_update 对象</li>
</ul>
例如
$query = db::update('employee'); // update `employee`
<h3>删除</h3>
<ul>
<li><strong>目的</strong>-生成查询的删除部分</li>
<li><strong>参数</strong>-</li>
<li><strong>$table_name</strong>-数据库表名</li>
<li><strong>返回</strong>-返回 database_query_builder_delete 对象</li>
</ul>
例如
$query = db::delete('employee'); // delete from 'employee'
<h2>查询接口</h2>
<strong>database_query</strong> 提供了一个选项来设置数据库连接、执行查询并将结果作为关联数组或对象获取。让我们看看 database_query 类提供的方法。
<h3>set_connection</h3>
<ul>
<li><strong>目的</strong>-设置对其执行查询的数据库(数据库连接详细信息)</li>
<li><strong>参数</strong>-$db-数据库连接名称</li>
<li><strong>返回</strong>-返回<em>database_query</em> 对象</li>
</ul>
例如
$query = db::query('delete * from employee', db::delete);
$query->set_connection('2nd-db');
<h3>参数</h3>
<ul>
<li><strong>目的</strong>-设置查询对象中定义的参数值</li>
<li><strong>参数</strong>-</li>
<li><strong>$param</strong>-参数名称;</li>
<li><strong>$value</strong>-参数的值</li>
<li><strong>返回</strong>-返回<em>database_query</em> 对象</li>
</ul>
例如
// set some variables
$table = 'employee';
$id = 1;
$name = 'jon';
// don't use
$query = db::query('select * from '.$table.'. where id = '.$id.' and name = "'.$name.'"');
// but use
$query = db::query('select * from :tablename where id = :id and name = :name');
$query->param('tablename', 'employee');
$query->param('id', $id);
$query->param('name', $name);
<h3>类似方法</h3>
<strong>parameters</strong> 是一个类似的对象,只是它提供了一次给出多个值的选项。
$query->parameters (array(
'tablename' => $table,
'id' => $id,
'name' => $name
});
<h3>绑定</h3>
<ul>
<li><strong>目的</strong>-将变量设置为查询对象中定义的参数</li>
<li><strong>参数</strong>-</li>
<li><strong>$param</strong>-参数名称</li>
<li><strong>$var</strong>-将参数绑定到的变量</li>
<li><strong>返回</strong>-返回<em>database_query</em> 对象</li>
</ul>
例如
// bind a query parameter
$table = 'employee';
$query = db::query('delete * from :tablename', db::delete);
$query->bind('tablename', $table);
// update the variable
$table = 'employee_salary';
// delete * from `employee_salary`;
$sql = $query->compile();
<h3>编译</h3>
<ul>
<li><strong>目的</strong>-将定义的查询对象编译为 sql 查询</li>
<li><strong>参数</strong>-</li>
<li><strong>$db</strong>-连接字符串,可选</li>
<li><strong>退货</strong>-</li>
</ul>
例如
// assign a value to a query parameter
$table = 'employee';
$query = db::query('delete * from :tablename', db::delete);
$query->param('tablename', $table);
// compile the query, returns: delete * from employee
$sql = $query->compile();
<h3>执行</h3>
<ul>
<li><strong>目的</strong>-执行查询对象中定义的查询并返回结果</li>
<li><strong>参数</strong>-</li>
<li><strong>$db</strong>-数据库连接名称</li>
<li><strong>返回</strong>-返回结果</li>
</ul>
例如
// assign a value to a query parameter
$table = 'employee';
$query = db::query('delete * from :tablename', db::delete);
$query->param('tablename', $table);
// execute the query
$query->execute();
<h3>as_assoc</h3>
<ul>
<li><strong>目的</strong>-将返回类型设置为关联数组而不是对象</li>
<li><strong>参数</strong>-无</li>
<li><strong>返回</strong>-返回当前对象</li>
</ul>
例如
$query = db::query('select * from employee', db::select);
$result = $query->as_assoc()->execute();
foreach ($result as $row) {
echo $row['id'];
}
<h3>as_object</h3>
<ul>
<li><strong>目的</strong>-将返回类型设置为对象而不是关联数组</li>
<li><strong>参数</strong>-无</li>
<li><strong>返回</strong>-返回当前对象</li>
</ul>
例如
$query = db::query('select * from employee', db::select);
$result = $query->as_object()->execute();
foreach ($result as $row) {
echo $row->id;
}
// have orm model objects return instead
$result = $query->as_object('model_employee')->execute();
<h2>查询生成器 api</h2>
查询构建器 <em>(query_builder)</em> 基于类提供动态构建 sql 查询的选项。它有四个类,每个类选择 <em>(query_builder_select)</em>、插入 <em>(query_builder_insert)</em>、更新 <em>(query_builder_update)</em>和删除 <em>(query_builder_delete )</em> 查询。这些类派生自 <em>query_builder_where</em> 类(生成条件的选项),该类本身派生自所有类的基础 <em>query_builder</em>。
让我们看看 query_builder 类提供的方法。
<h3>select</h3>
<ul>
<li><strong>目的</strong>-生成选择查询的列。</li>
<li><strong>参数</strong>-</li>
<li><strong>$columns</strong>-列列表,可选</li>
<li><strong>返回</strong>-返回当前实例</li>
</ul>
例如
$query = db::select('name') // select `name`
$query = db::select(array('first_name', 'name')) // select `first_name` as `name`
<h3>from</h3>
<ul>
<li><strong>目的</strong>-生成选择查询的表详细信息</li>
<li><strong>参数</strong>-</li>
<li><strong>$tables</strong>-表格列表</li>
<li><strong>返回</strong>-返回当前实例</li>
</ul>
例如
$query = db::select('name')->from('employee') // select `name` from `employee`
<h3>where</h3>
<ul>
<li><strong>目的</strong>-生成选择、插入和更新查询的条件</li>
<li><strong>参数</strong>-</li>
<li><strong>$column</strong>-列名或数组 ($column, $alias);</li>
<li><strong>$op</strong>-逻辑运算符,=、!=、in、between 和 like,可选;</li>
<li><strong>$value</strong>-列值</li>
<li><strong>返回</strong>-返回当前实例</li>
</ul>
例如
$query = db::select('name')->from('employee')
$query = $query->where('name', '=', 'jon');
// select `name` from `employee` where `name` = `jon`;
<h3>类似方法</h3>
类似的方法有 where_open(), and_where_open(), or_where_open(), where_close(), and_where_close(), or_where_close()。它们类似于 where() 方法,只是它们在条件周围添加了额外的关键字和括号。以下是示例代码。
$query = db::select('*')->from('employee');
$query->where('email', 'like', '%@gmail.com');
$query->or_where_open();
$query->where('name', 'jon');
$query->and_where('surname', 'peter');
$query->or_where_close();
// select * from `employee` where `email` like "%gmail.com" or
(`name` = "jon" and `surname` = "peter")
<h3>join</h3>
<ul>
<li><strong>目的</strong>-生成选择查询的表连接</li>
<li><strong>参数</strong>-</li>
<li><strong>$table</strong>-表名或数组($table, $alias);</li>
<li><strong>$type</strong>-连接类型(left、right、inner 等)</li>
<li><strong>返回</strong>-返回当前实例</li>
</ul>
<strong>示例:</strong>
$query = db::select('name')->from('employee')->join('employee_salary')
// select `name` from `employee` join `employee_salary`
<h3>on</h3>
<ul>
<li><strong>目的</strong>-在选择查询中生成连接条件</li>
<li><strong>参数</strong>-</li>
<li><strong>$c1</strong>-表名或在数组中有别名的表名;</li>
<li><strong>$op</strong>-逻辑运算符;</li>
<li><strong>$c2</strong>-表名或在数组中有别名的表名</li>
<li><strong>返回</strong>-返回当前实例</li>
</ul>
例如
$query = db::select('name')->from('employee')->join('employee_salary')
$query = $query->on('employee.employee_id', '=', 'employee_salary.employee_id')
// select `name` from `employee` join `employee_salary` on
// `employee.employee_id` = `employee_salary.employee_id`
<h3>类似方法</h3>
相关方法有and_on()和or_on()。它们与 on() 类似,只是它们在连接周围添加了额外的关键字和括号。
<h3>group_by</h3>
<ul>
<li><strong>目的</strong>-按查询生成分组</li>
<li><strong>参数</strong>-<strong>$columns</strong>-用于对结果进行分组的列名</li>
<li><strong>返回</strong>-返回当前实例</li>
</ul>
例如
$query = db::select('name')->from('employee')
$query = $query->group_by('name');
// select `name` from `employee` group by `name`
<h3>having</h3>
<ul>
<li><strong>目的</strong>-根据 sql 查询条件生成分组</li>
<li><strong>参数</strong>-<strong>$column</strong>-列名或数组( $column, $alias ); <strong>$op</strong>-逻辑运算符,=、!=、in、between 和 like,可选; <strong>$value</strong>-列值</li>
<li><strong>返回</strong>-返回当前实例</li>
</ul>
<strong>示例:</strong>
$query = db::select('name')->from('employee')
$query = $query->group_by('name');
$query = $query->having('name', '!=', 'jon');
// select `name` from `employee` group by `name` having `name` != `jon`
<h3>类似方法</h3>
类似的方法有having_open()、and_sharing_open()、or_sharing_open()、has_have_close()、and_sharing_close()、or_sharing_close()。除了它们在条件周围添加额外的关键字和括号之外,它们与 have() 方法类似。
<h3>reset</h3>
<ul>
<li><strong>目的</strong>-重置查询</li>
<li><strong>参数</strong>-无</li>
<li><strong>返回</strong>-返回当前实例</li>
</ul>
例如
$query = db::select('name')->from('employee')
$query->reset()
$query = db::select('name')->from('employee_salary')
// select `name` from `employee_salary`
<h3>dbutil 类</h3>
dbutil 类提供管理和执行日常数据库操作的选项。一些重要的方法如下:
<ul>
<li>set_connection-设置默认连接</li>
</ul>
dbutil::set_connection('new_database'); <ul>
<li>create_database-创建数据库。</li>
</ul>
dbutil::create_database('my_database'); <ul>
<li>drop_database-删除数据库。</li>
</ul>
dbutil::drop_database('my_database'); <ul>
<li>table_exists-检查给定的表是否存在。</li>
</ul>
if(dbutil::table_exists('my_table')) {
// table exists
} else {
// table does not exist, create it!
} <ul>
<li>drop_table-删除一个表。</li>
</ul>
dbutil::drop_table('my_table'); <ul>
<li>create_table-创建一个表。</li>
</ul>
\dbutil::create_table (
'users',
array (
'id' => array('type' => 'int', 'auto_increment' => true),
'name' => array('type' => 'text'),
),
);
<h2>orm 工具包</h2>
fuelphp 使用基于流行的 <strong>活动记录模式</strong>的 orm 概念提供高级数据库层。该工具包包含在应用程序中,但默认情况下未配置。它被捆绑成一个包,包名是orm。我们可以在主配置文件 <strong>fuel/app/config/config.php</strong>中添加如下配置来加载orm工具包。
'always_load' => array (
'packages' => array (
'orm',
),
),
<h3>创建模型</h3>
orm 提供基础模型类 orm\model。我们需要使用 orm 模型扩展我们的模型以使用 orm 功能。以下是示例代码。
class model_employee extends orm\model {}
<h3>configuration</h3>
orm 提供了一组设置来配置模型以使用 orm 功能。它们如下:
<strong>connection</strong>-在模型中设置静态 <em>_connection</em> 属性以指定连接名称。
class model_employee extends orm\model {
protected static $_connection = "production";
} <strong>表名</strong>-在模型中设置静态 <em>_table_name</em> 属性以指定后端表的表名。
class model_employee extends orm\model {
protected static $_table_name = 'employee';
} <strong>primary key</strong>-在模型中设置静态 <em>_primary_key</em> 属性以指定后端表的主键。
class model_employee extends orm\model {
protected static $_primary_key = array('id');
} <strong>columns</strong>-在模型中设置静态 _properties 属性以指定后端表的列。支持数据类型、标签、验证、表单元素等
class model_employee extends orm\model {
protected static $_properties = array (
'id',
'name' => array (
'data_type' => 'varchar',
'label' => 'employee name',
'validation' => array (
'required',
'min_length' => array(3),
'max_length' > array(80)
),
'form' => array (
'type' => 'text'
),
),
'age' => array (
'data_type' => 'int',
'label' => 'employee age',
'validation' => array (
'required',
),
'form' => array (
'type' => 'text'
),
),
);
} <strong>条件</strong>-设置静态 <em>_conditions</em> 属性以设置条件和按选项排序。
class model_employee extends orm\model {
protected static $_conditions = array (
'order_by' => array('id' => 'desc'),
'where' => array (
array('is_active', > true),
),
);
} <strong>observers</strong>- <em>orm</em> 提供基于观察者的事件系统来为特定事件添加行为。要添加行为,首先在模型中设置 <em>_observers</em> 属性。然后,将行为定义为一个类并将其与事件一起设置在 <em>_observers</em> 属性中。如果未指定事件,则将为所有事件调用该行为。我们也可以指定多种行为。
class model_employee {
protected static $_observers = array (
'example', // will call observer_example class for all events
'orm\\observer_createdon' => array (
'events' => array('before_insert'),
// will only call orm\observer_createdon at before_insert event
)
);
}
<h3>create</h3>
一旦我们配置了模型,我们就可以立即开始使用这些方法。 <em>orm</em> 提供了一个 <em>save</em> 方法来将对象保存到数据库中。我们可以使用配置的属性设置数据如下:
// option 1
$new = new model_employee();
$new->name = 'jon';
$new->save();
// option 2, use forge instead of new
$new = model_employee::forge();
$new->name = 'jon';
$new->save();
// option 3, use array for properties
$props = array('name' => 'jon');
$new = model_employee::forge($props);
$new>save();
<h3>read</h3>
orm 提供了一个方法,find 从数据库中获取数据并绑定到对象中。 find 方法的工作取决于输入参数。让我们看看不同的选项:
<strong>by primary key</strong>-指定主键通过匹配配置表的主键返回记录。
$employee = model_employee::find(1);
<strong>first/last record</strong>-指定"first"或"last"将分别获取第一条记录或最后一条记录。我们也可以通过选项传递订单。
$entry = model_employee::find('first');
$entry = model_article::find('last', array('order_by' => 'id')); <strong>all</strong>-指定"all"将从配置的表中获取所有记录。我们可以按选项和条件指定顺序。
$entry = model_employee::find('all');
$entry = model_article::find ('all', array (
'where' => array (
array ('name', 'jon'),
),
'order_by' => array ('id' => 'desc'),
)); 我们可以使用基本数据库工具包的查询 api 以及高级搜索选项的模型,如下所示。
$query = model_employee::query()->where('category_id', 1)->order_by('date', 'desc');
$number_of_employees = $query->count();
$latest_employee = $query->max('id');
$young_employee = $query->min('age');
$newest_employee = $query->get_one();
$employees = $query->limit(15)->get();
<h3>更新</h3>
更新模型与创建模型相同,只是不是创建新模型,而是使用 find 方法获取要更新的模型,更新属性,然后调用 save 方法,如下所示。
$entry = model_employee:find(4);
$entry->name = 'peter';
$entry->save();
<h3>删除</h3>
orm 提供了删除模型的删除方法。只需获取对象并调用删除方法即可。
$entry = model_employee:find(4);
$entry->delete();
<h2>工作示例</h2>
让我们在本章中创建一个工作示例来了解模型和数据库。
<h3>创建数据库</h3>
使用以下命令在 mysql 服务器中创建一个新数据库。
create database tutorialspoint_fueldb
然后,使用以下命令在数据库中创建一个表。
create table employee(id int primary key, name varchar(20), age int not null);
<h3>配置数据库</h3>
让我们使用数据库配置文件 *fuel/app/config/db.php 来配置数据库。添加以下更改以连接 mysql 服务器。
return array (
'development' =--> array (
'type' => 'mysqli',
'connection' => array (
'hostname' => 'localhost',
'port' => '3306',
'database' => 'tutorialspoint_fueldb',
'username' => 'root',
'password' => 'pass',
'persistent' => false,
'compress' => false,
),
'identifier' => '`',
'table_prefix' => '',
'charset' => 'utf8',
'enable_cache' => true,
'profiling' => false,
'readonly' => false,
),
'production' => array (
'type' => 'mysqli',
'connection' => array (
'hostname' => 'localhost',
'port' => '3306',
'database' => 'tutorialspoint_fueldb',
'username' => 'root',
'password' => 'pass',
'persistent' => false,
'compress' => false,
),
'identifier' => '`',
'table_prefix' => '',
'charset' => 'utf8',
'enable_cache' => true,
'profiling' => false,
'readonly' => false,
),
);
<h3>包含 orm 包</h3>
更新主配置文件 <strong>fuel/app/config/config.php</strong> 通过添加以下配置来包含 orm 包。
'always_load' => array (
'packages' => array (
'orm'
),
), 现在,您的应用程序中启用了 orm
<h3>创建员工模型</h3>
在模型文件夹 <strong>"fuel/app/classes/model"</strong>下新建一个模型employee,定义如下。
<strong>employee.php</strong>
class model_employee extends orm\model {
protected static $_connection = 'production';
protected static $_table_name = 'employee';
protected static $_primary_key = array('id');
protected static $_properties = array (
'id',
'name' =--> array (
'data_type' => 'varchar',
'label' => 'employee name',
'form' => array (
'type' => 'text'
),
),
'age' => array (
'data_type' => 'int',
'label' => 'employee age',
'form' => array (
'type' => 'text'
),
),
);
}
<h3>create action</h3>
在位于 <strong>fuel/app/classes/controller/employee.php</strong> 的 employee 控制器中创建新动作, <strong>action_model</strong>,如下所示。
class controller_employee extends controller {
public function action_model() {
// db based sql command to delete all employees
$query = db::query('delete from `employee`');
$query->execute('production');
// orm based query to add new employees
$model = new model_employee();
$model->name = "john";
$model->age = 25;
$model->save();
$model = new model_employee();
$model->name = "peter";
$model->age = 20;
$model->save();
// orm based query to fetch all employee data
$data = array();
$data['emps'] = model_employee::find('all');
return response::forge(view::forge('employee/model', $data));
}
}
<h3>创建视图</h3>
现在,创建一个位于 <strong>"fuel/app/views/employee"</strong> 的视图文件 <strong>model.php</strong>。在文件中添加以下更改。
<ul>
foreach($emps as $emp) {
<li> echo $emp['name']; </li>
}
</ul>
现在,请求 url, <strong>http://localhost:8080/employee/model</strong>,它将产生以下结果。
<h3>结果</h3>
<img src="/public/core/edit/php/../attached/20231217205331_95671.jpg" alt="" border="0" />
<h3><a href="/s7900103/fuelphp 表单编程.html">下一节:fuelphp 表单编程</a></h3>
<a class="bottom-summary-prompt" href="/php/php_sz/153.html"><h3>fuelphp 教程</h3>
</a>


