alnutile/entity_decorator

一个用于美化实体装饰的Drupal 7模块。

dev-master 2014-06-24 13:58 UTC

This package is auto-updated.

Last update: 2024-09-06 08:43:43 UTC


README

一个用于美化实体装饰的Drupal 7模块。

Packagist在这里https://packagist.org.cn/packages/alnutile/entity_decorator

序言

厌倦了输入嵌套数组的代码来处理你的字段吗?

 $item_id = $node->{$this->field_name}[LANGUAGE_NONE][0]['value'];

当然,所以你使用了实体API

这是一个改进,但你可能发现自己在大量输入entity_metadata_wrapper

$wrapper = entity_metadata_wrapper('node', $node);

你可能还想要将实体作为对象来处理,并扩展它们以添加自己的自定义方法。

实体装饰器旨在允许你为任何实体或节点类型创建装饰器对象,并提供一个美观、简洁的接口。

它还创建了一个新的查询实体和节点类型的新接口,希望这会更简洁、直观。

一个常见的用例可能是,你想使用ECK创建自定义实体类型,然后基于你创建的字段和属性为这些类型创建自定义方法。

实体装饰器应与自定义实体和节点类型一样好,无论你更喜欢哪种装饰。

用法

使用composer_manager安装和更新composer

创建装饰器类很简单。创建一个这样的类。

use EntityDecorator;

class MyDecoratedNodeType extends EntityDecorator {
  static public $entityType = 'node';
  static public $bundle     = 'my_node_type';
}

就是这样。所有实体装饰器的好处都立即由你的新类提供!

此外,你可以添加任何你喜欢的自定义方法到你的类中。

现在你可以编写这样的代码

$node = new MyDecoratedNodeType();
$node->set_title('The title');
$node->set_field_my_custom_field('My value');
$node->callACustomMethod();
$node->save();

这难道不是很简洁吗?在网站上没有深层次的数组或entity_metadata_wrapper调用。

注意:一些元编程魔法创建了一些方法。调用set_*get_*将作为任何属性的获取或设置器。实体装饰器大多数情况下抽象了属性和字段之间的区别。

由于这实现了装饰器模式,你仍然可以像装饰器类包裹的实例一样访问你实体的所有属性和方法。

关系和引用

如果你有一个引用实体的字段,那么当你调用时,实体装饰器会返回预期的实体

$node->get_field_my_entity();

$node->get('field_my_entity');

如果你正在获取的实体也有一个用于包装它的entity_decorator类,你可以调用

$node->getDecorated('field_my_entity', 'class_name_that_decorates_it');

然后你会得到装饰过的实体。

这也在实体数组上有效,例如使用field_collection。所以

$node->getDecorated('field_my_field_collection', 'class_name_that_decorates_it');

将返回装饰过的field_collection项的数组。

查询

EntityFieldQuery有一个相当冗长的接口和难以记忆的语法。虽然实体装饰器的查找器尚未实现EntityFieldQuery的完整功能,但它们应该更简单、更容易使用。

与EntityFieldQuery不同,这些查找器返回带有实例化实体的EntityDecorators。我们认为这很好。

示例

MyDecoratedNodeType::find(12345);

返回nid为12345的MyDecoratedNodeType,如果不存在则返回null。

MyDecoratedNodeType::find_by_field_my_custom_field('Some value')->execute();

返回一个数组,其中'field_my_custom_field'的值为'Some value'的MyDecoratedNodeTypes。

MyDecoratedNodeType::find_by_field_my_custom_field(array('Some value', 'another value'))->execute();

返回一个数组,其中'field_my_custom_field'的值为'Some value'或'another value'的MyDecoratedNodeTypes。

并且你可以将它们链接起来...

MyDecoratedNodeType::find_by_field_my_custom_field('Some value')->find_by_title('other value')->execute();

返回一个包含 MyDecoratedNodeTypes 的数组,其中 'field_my_custom_field' 字段的值为 'Some value' 且 'title' 字段的值为 'other value'。是的,查找器也抽象了属性/字段之间的区别。

并且排序...

MyDecoratedNodeType::find_by_field_my_custom_field('Some value')->orderBy('field_another_field', 'ASC');

返回一个包含 MyDecoratedNodeType 的数组,其中 'field_my_custom_field' 字段的值为 'Some value',并且按 field_another_field 字段的值排序。

你可能只想获取一条记录

MyDecoratedNodeType::find_first_by_field_my_custom_field('Some value');

这将返回第一个 'field_my_custom_field' 字段的值为 'Some value' 的记录。 注意 不需要使用 find_first_by_* 调用 execute 方法,因为按照定义,查询可以立即执行。