Communauté Elgg francophone

Créer un compteAide  
Connexion

Entities - les "entités" Elgg

Les "entités" Elgg sont des représentations "objet" des données : un site, un groupe, un utilisateur ou un "object" blog, page ou marque-page est une entité Elgg ("Elgg entity")

 

Elgg définit 4 principaux types d'entités : ElggSite, ElggUser, ElggObject et ElggGroup. A titre d'exemple, voyons comment créer un objet :

Créer un objet

Pour créer un objet dans votre code, vous devez créer une instance ElggObject. Sa définition est faite simplement en ajoutant des variables et des propriétés. Les propriétés de base sont :

  • guid Le GUID de l'entité; défini automatiquement
  • owner_guid Le GUID de l'utilisateur propriétaire
  • site_guid Le GUID du site propriétaire. C'est défini automatiquement quand une instance de ElggObject est créée.
  • subtype un mot unique définissant le type d'objet, par exemple blog
  • access_id un nombre entier représentant le niveau d'accès de l'objet
  • title Le titre de l'objet
  • description La description de l'objet

Le sous-type (subtype) est une propriété spéciale. C'est une chaine arbitraire de caractères décrivant ce que l'objet est. Par exemple, si vous écrivez un plugin de blog, votre sous-type peut être blog. Rendre ce sous-type est une bonne pratique, pour éviter que d'autres plugins tentent d'utiliser le même sous-type. Dans le cadre de ce document, partons du principe que nous construisons un simple forume. Le sous-type serait donc forum:

$object = new ElggObject();
 
$object->subtype = "forum";
 
$object->access_id = 2;
 
$object->save();

access_id est une autre propréité importante. Si vous ne la définissez pas, votre objet sera privé, et seul l'utilisateur qui le crée pourra l'utiliser. Les valeurs spécifiques pour access_id sont : 0 (privé), 1 (membres loggés), 2 (public).

Sauvegarder avec succès l'objet viendra automatiquement peupler $object->id property. Si vous changez d'autres propriétés de base, vous pouvez appelez à nouveau $object->save() , qui mettra à jour la base de données pour vous. Lorsque vous aurez sauvegardé votre objet dans la base de données - et seulement à ce moment - vous pourrez définir des metadatas pour lui. Un metadata a un nom arbitraire et une valeur, et peut être défini de la même manière qu'une propriété standard. Disons que nous voulons que définir que le GUID parent de notre post sur le forum est 0. 

$object->parent_guid = 0;

If you assign an array, all the values will be set for that metadata. This is how, for example, you set tags.

Loading an object

If you know the GUID

If you know the GUID of your object, you can simply load it with get_entity($guid), where $guid is the object GUID. The object it returns will be autopopulated with the object's properties, which can be read with $object->parent_guid to retrieve the parent GUID we had set in the previous example.

But what if you don't know the GUID? There are several options.

Get users by user, subtype or site

If you know the user ID you want to get objects for, or the subtype, or the site, you have several options. The easiest is probably to call the procedural function get_entities($entity_type, $subtype, $owner_guid) where entity type is user, object or site. You can leave user_id to 0 to get all objects and leave subtype or type blank to get objects of all types/subtypes. Limit defaults to 10; offset to 0. This will return an array of ElggEntity objects that you can iterate through.

If you already have an ElggUser – eg $_SESSION['user'], which always has the current user's object when you're logged in – you can simply use $object_array = $user->getObjects($subtype, $limit, $offset).

But what about getting objects with a particular piece of metadata? Let's say we want everything with a parent_guid of 0.

Get objects by metadata

Currently two functions are available to retrieve entities by metadata, get_entities_from_metadata() and get_entities_from_metadata_multi(). The former can be used to get entities based on a single piece of metadata, the latter can handle multiple metedata values. Following our example, to retrieve all entities with parent_guid of 0, you would use the following call:

get_entities_from_metadata('parent_guid', 0, 'object');

This will return an array of entities you can iterate through.

Displaying entities

In order for entities to be displayed in listing functions you need to provide a view for the entity in the views system.

To display an entity, create a view EntityType/subtype where EntityType is one of the following:

  • object: for entities derived from ElggObject
  • user: for entities derived from ElggUser
  • site: for entities derived from ElggSite
  • group: for entities derived from ElggGroup

A default view for all entities has already been created, this is called EntityType/default.

Entity Icons

Entities all have a method called ->getIcon($size).

This method accepts a $size variable, which can be either 'large', 'medium', 'small' or 'tiny'.

The method triggers a plugin hook - 'entity:icon:url'. This is passed the following parameters:

  • 'entity' : The entity in question
  • 'viewtype' : The type of view e.g. 'default' or 'mobile'.
  • 'size' : The size.

The hook should return a url.

Hooks have already been defined, and will look in the following places for default values:

  • views/$viewtype/graphics/icons/$type/$subtype/$size.png
  • views/$viewtype/graphics/icons/$type/default/$size.png
  • views/$viewtype/graphics/icons/default/$size.png

Where

  • $viewtype : The type of view e.g. 'default' or 'mobile'.
  • $type : The type of entity - group, site, user, object.
  • $subtype : Subtype of $type, e.g. blog, page.
  • $size : Size - 'large', 'medium', 'small' or 'tiny'

Adding, reading and deleting annotations

Annotations could for example be comments and ratings. To annotate an entity you can use the object's annotate(), which expects four parameters, name, which is the name of the annotation type, value, which is the value of the annotation, access_id and owner_guid. For example, to add a comment to a blog post you could use:

$entity->annotate('comments', 'Hi!  I'm making a comment.', 2);

To retrieve the comments on the blog post, use $blogpost->getAnnotations('comments') and if you want to delete an annotation, you can operate on the ElggAnnotation class, eg $annotation->delete().

Retrieving an annotation can be done with get_annotation() if you have the annotation's ID. Deleting it is simply a matter of calling the delete() function of the annotation object. If you delete an ElggEntity, whether it be a site, user, object or group all its metadata and annotations will be automatically deleted.

Extending ElggEntity

If you derive from one of the Elgg core classes, you'll need to tell Elgg how to properly instantiate the new type of object so that get_entity() et al. will return the appropriate PHP class. For example, if I customize ElggGroup in a class called "Committee", I need to make Elgg aware of the new mapping. Following is an example class extension:

// Class source
class Committee extends ElggGroup {
 
protected function initialise_attributes() {
parent::initialise_attributes();
$this->attributes['subtype'] = 'committee';
}
 
public function __construct($guid = null) {
parent::__construct($guid);
}
 
// more customizations here
}
 
function committee_init() {
register_entity_type('group', 'committee');
// This operation only affects the db on the first call for this subtype
// If you change the class name, you'll have to hand-edit the db
add_subtype('group', 'committee', 'Committee');
}
 
register_elgg_event_handler('init', 'system', 'committee_init');

Now if you invoke get_entity() with the GUID of a committee object, you'll get back an object of type Committee.

This template was extracted from the definition of ElggFile.

Advanced features

Entity Icons

A url for an icon representing a given entity can be retrieved by the getIcon() method.

This is handy as it provides a generic interface which allows the Elgg framework to draw an icon for your data - it also allows you to override icons for existing data types - for example providing Gravatar support for user icons.

If no icon can be provided for the data type a default one is used, defined either by your current theme or the Elgg default.

Overriding the url for a specific instance

To override the icon of a specific instance of an entity in a non-permanent and one off way, you can use the entity's setIcon() method.

Replacing icons via the views interface

If you want to provide an icon for a new data type, or override an existing one you can do this simply through the views interface.

Views are in the format:

icon/[TYPE]/[SUBTYPE]/[SIZE]

Where:

  • [TYPE] is the elgg type of the object - "user", "group", "object" or "site".
  • [SUBTYPE] is the specific subtype of the object, or "default" for the default icon for the given type.
  • [SIZE] the size, one of the following "master", "large", "medium", "small", "topbar" or "tiny".

This view should contain the URL to the image only.

Overriding icons via a handler

The final way to replace icons is via a handler to a plugin hook.

This method lets you perform some additional logic in order to decide better which url to return.

The hook triggered is:

trigger_plugin_hook('entity:icon:url', $entity->getType(), array('entity' => $entity, 'viewtype' => $viewtype, 'size' => $size));

Entity URLs

Entity urls are provided by the getURL() interface and provide the Elgg framework with a common way of directing users to the appropriate display handler for any given object.

For example, a profile page in the case of users.

The url is set using the register_entity_url_handler() function. The function you register must return the appropriate url for the given type - this itself can be an address set up by a page handler.

The default handler is to use the default export interface.

Also see