thomasjbradley/micromodel

该包已被废弃且不再维护。未建议替代包。

MicroModel:一个非常基础的ORM类似表单和表映射器,用于与Silex、Symfony Forms和Doctrine DBAL一起工作;支持无关系的单表。

v1.1.3 2012-08-09 19:58 UTC

This package is not auto-updated.

Last update: 2020-04-03 16:14:03 UTC


README

一个非常基础的ORM类似表单和表映射器,用于与Silex、Symfony Forms和Doctrine DBAL一起工作;支持无关系的单表。

示例表

以下是我们将用于其余代码示例的表。

`planets`

| id       | name    | orbital_period | last_updated |
| (PK, AI) | (text)  | (number)       | (text)       |
------------------------------------------------------
| 1        | Mercury | 87.97          | 1982-10-28   |
| 2        | Venus   | 224.70         | 1980-05-21   |
| 3        | Earth   | 365.25         | 1981-06-04   |

如何使用

  1. 使用Composer安装。

    {
    	"require": {
    		"thomasjbradley/micromodel": "<2.0.0"
    	}
    }
  2. 在Silex应用程序中创建一个扩展MicroModel的PHP类。 类名必须与表名相同。 大小写无关,类名/表名将被转换为小写。

    <?php
    
    class Planets extends MicroModel
    {
    	public function defineSchema ()
    	{
    		// Define all the table's fields
    	}
    }
  3. 然后创建一个新的模型实例,传入Silex\Application。

    <?php
    $app = new Silex\Application();
    $planets = new Planets($app);
    $planetsList = $planets->all();

定义字段

在定义字段时,选项数组继承自 Symfony\Form 选项数组。

始终首先定义主键字段。

<?php

use Symfony\Component\Validator\Constraints as Assert;

class Planets extends MicroModel
{
	public function defineSchema ()
	{
		// The primary key MUST always come first
		$this->defineField('id', 'integer');

		$this->defineField('name', 'text', array(
			'constraints' => array(new Assert\NotBlank())
			, 'set' => function ($val) {
				return filter_var($val, FILTER_SANITIZE_STRING);
			}
		));

		$this->defineField('orbital_period', 'number', array(
			'constraints' => array(new Assert\Number())
			, 'precision' => 2
			, 'set' => function ($val) {
				return filter_var($val, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
			}
		));

		$this->defineField('last_updated', 'date', array(
			'constraints' => array(new Assert\NotBlank(), new Assert\Date())
			, 'format' => 'yyyy-MM-dd'
			, 'display' => false
			, 'set' => function ($val) {
				if (is_object($val)) return $val;
				return new DateTime($val);
			}
		));
	}
}

字段定义额外选项

MicroModel为数组添加了一些额外选项。

  • set (函数) — 可选的setter函数。允许进行数据类型转换和清理。
  • display (布尔值) — 可选;字段是否应在表单中显示。

方法

☛ __construct( Silex\Application $app [, mixed $clauses = null ] )

设置模型,并可选地通过指定 $clauses 立即读取单个项。

  • $app — Silex\Application 对象。
  • $clauses — 直接传递给 read()。有关更多详细信息,请参阅 read()
<?php
$planets = new Planets($app, 1);
echo $planets->name; // Mercury

☛ defineField( $name [, string $type = 'text' [, array $options = array() ]] )

在模型上定义一个新字段以匹配表中的字段。 通常在 defineSchema() 方法内调用。 请参阅定义字段

  • $name — 字段名称,与表的字段名称拼写完全相同。
  • $typeSymfony\Form 字段类型之一。它们与 Doctrine\DBAL 字段类型非常匹配。
  • $options — 任何 Symphony\Form 字段选项。有关更多选项,请参阅 字段注册额外选项

@return$this

☛ find( [ string|array $order = null [, array $where = array() ]] )

从表中获取一组结果,可选项进行排序。没有参数时,find()将返回数据库中的所有条目。将返回一个包含模型对象的数组。

  • $order — 排序子句的字段名称和方向。
  • $where — WHERE子句条件的数组,格式如下:array('field', 'comparison', 'value')

返回值 — 一个对象数组,每个对象都是你的模型的一个实例。

<?php
$planets = new Planets($app);
$planetsList = $planets->find();

foreach ($planetsList as $planet) {
	echo $planet->name;
}

// Since each item in the array is your model object, you could do this
$planetsList[0]->name = 'Neptune';
$planetsList[0]->update();

// Using the $order argument
$planets->find('name ASC');
$planets->find(array('name ASC', 'orbital_period DESC'));

// Using the $where argument
$planets->find(null, array(
	array('orbital_period', '>', 200)
	, array('name', 'LIKE', '%e%')
));

// Using $order and $where
$planets->find('name ASC', array(
	array('orbital_period', '>', 200)
));

☛ create()

使用当前对象的属性值将其插入到表中。插入后,主键字段使用lastInsertId填充。在尝试创建之前不会验证数据。

@return$this

<?php
$planets = new Planets($app);
$planets->name = 'Jupiter';
$planets->orbital_period = 4332.59;
$planets->last_updated = new DateTime();
$planets->create();
echo $planets->id; // 4

☛ read( mixed $clauses )

从表中读取单个条目,将所有字段转换为对象的属性。

  • $clauses — 读取表中单个条目的条件。
    • int|string — 单个项目的唯一键值。
    • array — WHERE子句条件的数组,格式如下:array('field', 'comparison', 'value')

@return$this

<?php
$planets = new Planets($app);

// Use the primary key to select an item
// Equates to WHERE id = 1
$planet = $planets->read(1);
echo $planet->name; // Mercury

// Set up a WHERE clause with arrays
// Equates to WHERE name = 'Earth'
$planet = $planets->read(array(
	array('name', '=', 'Earth')
));
echo $planet->name; // Earth

☛ update()

使用属性值在表中更新当前对象。使用标记为主键的字段作为WHERE子句。在尝试更新之前不会验证数据。

@return$this

<?php
$planets = new Planets($app, 2);
$planets->last_updated = new DateTime();
$planets->update();

☛ delete()

从表中删除当前对象。使用标记为主键的字段作为WHERE子句。

@return$this

<?php
$planets = new Planets($app, 3);
$planets->delete();

☛ getForm( [ boolean $csrfProtection = true ] )

返回一个Symfony表单对象,使用字段注册的所有约束和选项。

  • $csrfProtection — 启用/禁用CSRF保护的标志;主要用于API。

返回值 — Symfony表单

<?php
$planets = new Planets($app, 1);
$form = $planets->getForm();
// $form->bind($request);
// $form->isValid();
// $form->createView();

// When writing a JSON API
$form = $planets->getForm(false);
// Symfony's form bind() method expects an array, so force json_decode to use associative arrays
$form->bind(json_decode($request->getContent(), true));

if ($form->isValid()) {
	$movie->create();
	$app->abort(204);
}

☛ jsonSerialize()

双重功能:返回一个关联数组中所有字段的简化版本,在PHP/5.4中它是JsonSerializer实现。

返回值 — 包含所有字段及其值的array

<?php
$planets = new Planets($app, 2);

// PHP/5.4
return $app->json($planets);

// PHP/5.3
return $app->json($planets->jsonSerialize());
// Because PHP/5.3 doesn't have the JsonSerializer interface
// Will work equally as well in PHP/5.4

☛ isValid()

将对象中的信息与字段约束进行验证。

返回值boolean

<?php
$planets = new Planets($app);
$planets->name = 'Saturn';
$planets->orbital_period = 10759.22;
$planets->last_updated = new DateTime();
$planets->isValid(); // true

☛ getErrors()

返回由Symfony表单生成的所有验证错误消息的数组。通常在需要查看错误消息时在isValid()之后调用。如果没有错误消息,则数组为空。

返回值array

许可证

MicroModel采用BSD 3-Clause许可证