Base de datos

Persiste contenido y opciones de usuarios mediante la API de almacenamiento genérico de Elgg.

Entidades

Crear un objeto

Para crear un objeto desde código, tiene que crear una instancia de ElggObject. Definir sus datos es simplemente cuestión de añadir variables o propiedades a la instancia. Las propiedades de serie son:

  • ``guid``: El identificador único de la entidad, definido de manera automática.
  • ``owner_guid``: El identificador único del usuario propietario del objeto.
  • ``site_guid``: El identificador único del sitio al que pertenece el objeto. Éste se define de manera automática al crear una instancia de ElggObject.
  • ``subtype``: Una cadena de texto arbitraria y sin espacios que define el tipo de objeto del que se trata, como blog.
  • ``access_id``: Un número entero que representa el nivel de acceso del objeto.
  • ``title``: El título del objeto.
  • ``description``: La descripción del objeto.

El subtipo del objeto es una propiedad especial. Se trata de una cadena de texto arbitraria que describe qué es el objeto. Por ejemplo, si estuviese escribiendo un complemento para blogs, su subtipo podría ser blog. Lo ideal es que la palabra sea única, de forma que otros complementos no la usen también de manera accidental. Para el propósito de esta documentación, partamos de la idea de crear un foro muy simple, para el que usaremos el subtipo forum («foro» en inglés):

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

access_id es otra propiedad importante. Se no le da usted valor a esta propiedad, el objeto será privado, y sólo el usuario creador del objeto podrá verlo. Elgg define constantes para valores especiales de access_id:

  • ACCESS_PRIVATE: Sólo el usuario propietario del objeto puede verlo.
  • ACCESS_FRIENDS: Sólo el usuario propietario del objeto y sus contactos pueden verlo.
  • ACCESS_LOGGED_IN: Cualquier usuario registrado puede verlo.
  • ACCESS_PUBLIC: Cualquier persona, con o sin cuenta en el sitio, puede verlo.

Al guardar el objeto, se le dará automáticamente un valor a su propiedad guid si la operación de guardado se completa correctamente. Si cambia más propiedades de serie, puede llamar al método save() del objeto de nuevo, y la base de datos se actualizará de acorde a sus cambios.

Puede definir metadatos en un objeto como haría con cualquier propiedad de serie. Digamos que queremos definir la edición (SKU) de un producto:

$object->SKU = 62784;

Si asigna un vector, todos los valores se definirán para ese metadato. Por ejemplo, así es como definiría etiquetas:

Los metadatos no se pueden persistir a la base de datos hasta que la entidad se ha guardado, pero por comodidad, ElggEntity puede cachearlos de manera interna y guardarlos al guardar la entidad.

Cargar un objeto

Por identificador

$entity = get_entity($guid);
if (!$entity) {
    // The entity does not exist or you're not allowed to access it.
}

¿Pero qué pasa si usted desconoce el identificador único? Pues existen varias opciones.

Por usuario, subtipo o sitio

Si conoce el identificador del usuario cuyos objetos está buscando, o el subtipo o el sitio de esos objetos, dispone de varias opciones para obtener esos objetos. La más fácil probablemente sea la de llamar a la función procedural elgg_get_entities:

$entities = elgg_get_entities(array(
    'type' => $entity_type,
    'subtype' => $subtype,
    'owner_guid' => $owner_guid,
));

Esto devolverá un vector de instancias de ElggEntity por el que usted puede iterar. elgg_get_entities usa divide los resultados en grupos de manera predeterminada, con un límite de 10 resultados por grupo, y empezando desde 0.

Puede omitir owner_guid para obtener todos los objetos u omitir el subtipo o el tipo para obtener objetos de todos los tipos o subtipos.

Si ya tiene una instancia de ElggUser —que puede obtener, por ejemplo, mediante elgg_get_logged_in_user_entity el objeto del usuario actual— puede usar:

$objects = $user->getObjects($subtype, $limit, $offset)

¿Pero qué hay de obtener objetos que tienen un metadato concreto?

Por metadatos

La función elgg_get_entities_from_metadata permite obtener entidades por metadatos de varias maneras.

By annotation

The function elgg_get_entities_from_annotations allows fetching entities with metadata in a variety of ways.

Nota

As of Elgg 1.10 the default behaviour of elgg_get_entities_from_annotations was brought inline with the rest of the elgg_get_entities* functions.

Pre Elgg 1.10 the sorting of the entities was based on the latest addition of an annotation (in $options your could add $options[“order_by”] = “maxtime ASC” or $options[“order_by”] = “maxtime DESC”. As of Elgg 1.10 this was changed to the creation time of the entity, just like the rest of the elgg_get_entities* functions. To get the old behaviour back add the following to your $options:

$options['selects'] = array('MAX(n_table.time_created) AS maxtime');
$options['group_by'] = 'n_table.entity_guid';
$options['order_by'] = 'maxtime ASC'

or

$options['order_by'] = 'maxtime DESC'

Mostrar entidades

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

Para mostrar una entidad, cree una vista llamada «TipoDeEntidad/subtipo» donde «TipoDeEntidad» es uno de los siguientes:

object, rara entidades derivadas de ElggObject; user, para entidades derivadas de ElggUser; site, para entidades derivadas de ElggSite; o group, para entidades derivadas de ElggGroup.

Ya se crea una vista predeterminada para todas las entidades, llamada «TipoDeEntidad/default».

Iconos de entidades

Entity icons can be saved from uploaded files, existing local files, or existing ElggFile objects. These methods save all sizes of icons defined in the system.

$object = new ElggObject();
$object->title = 'Example entity';
$object->description = 'An example object with an icon.';

// from an uploaded file
$object->saveIconFromUploadedFile('file_upload_input');

// from a local file
$object->saveIconFromLocalFile('/var/data/generic_icon.png');

// from a saved ElggFile object
$file = get_entity(123);
if ($file instanceof ElggFile) {
        $object->saveIconFromElggFile($file);
}

$object->save();
The following sizes exist by default:
  • master - 550px at longer edge (not upscaled)
  • large - 200px at longer edge (not upscaled)
  • medium - 100px square
  • small - 40px square
  • tiny - 25px square
  • topbar - 16px square

Use elgg_get_icon_sizes() to get all possible icon sizes for a specific entity type and subtype. The function triggers the entity:icon:sizes hook.

To check if an icon is set, use $object->hasIcon($size).

You can retrieve the URL of the generated icon with``ElggEntity::getIconURL($params)`` method. This method accepts a $params argument as an array that specifies the size, type, and provide additional context for the hook to determine the icon to serve. The method triggers the entity:icon:url hook.

Use elgg_view_entity_icon($entity, $size, $vars) to render an icon. This will scan the following locations for a view and include the first match to .

  1. views/$viewtype/icon/$type/$subtype.php
  2. views/$viewtype/icon/$type/default.php
  3. views/$viewtype/icon/default.php

Donde:

$viewtype
Type of view, e.g. 'default' or 'json'.
$type
Type of entity, e.g. 'group' or 'user'.
$subtype
Entity subtype, e.g. 'blog' or 'page'.

Icon methods support passing an icon type if an entity has more than one icon. For example, a user might have an avatar and a cover photo icon. You would pass 'cover_photo' as the icon type:

$object->saveIconFromUploadedFile('uploaded_photo', 'cover_photo');

$object->getIconUrl([
        'size' => 'medium',
        'type' => 'cover_photo'
]);

Note that custom icon types (e.g. cover photos) do not have preset sizes and coordinates. Use entity:<icon_type>:url hook to configure them.

By default icons will be stored in /icons/<icon_type>/<size>.jpg relative to entity’s directory on filestore. To provide an alternative location, use the entity:<icon_type>:file hook.

Añadir, leer y eliminar anotaciones

Las anotaciones se pueden usar por ejemplo para llevar un seguimiento de puntuación. Para añadir una anotación a una entidad puede usar el método annotate() del objeto. Por ejemplo, para darle a un artículo de blog una puntuación de 5, puede utilizar:

$blog_post->annotate('rating', 5);

Para obtener las puntuaciones del artículo, use $blogpost->getAnnotations('rating') y si quiere eliminar una de las anotaciones puede hacerlo sobre la clase ElggAnnotation usando el método $annotation->delete().

Para obtener una única anotación se puede usar get_annotation() siempre que disponga del identificador único de la anotación. Si elimina una instancia de ElggEntity de cualquier tipo, se eliminarán también y de manera automática todos sus metadatos, anotaciones y relaciones.

Extender ElggEntity

Si escribe una subclase de una de las clases fundamentales de Elgg, tendrá que informar a Elgg sobre cómo crear una instancia del nuevo tipo de objeto correctamente, de forma que get_entity() y otros métodos similares puedan devolver una clase de PHP en condiciones. Por ejemplo, si personaliza la clase ElggGroup en una subclase llamada Committee (comité), tiene que informar a Elgg sobre ella. Véase el siguiente ejemplo de extensión de una clase:

// Class source
class Committee extends ElggGroup {

    protected function initializeAttributes() {
        parent::initializeAttributes();
        $this->attributes['subtype'] = 'committee';
    }

    // more customizations here
}

function committee_init() {

    register_entity_type('group', 'committee');

    // Tell Elgg that group subtype "committee" should be loaded using the Committee class
    // If you ever change the name of the class, use update_subtype() to change it
    add_subtype('group', 'committee', 'Committee');
}

register_elgg_event_handler('init', 'system', 'committee_init');

Ahora, si llama a get_entity() con el identificador único de un objeto de comité, obtendrá un objeto de tipo Committee.

Este modelo se extrajo de la definición de ElggFile.

Funcionalidades avanzadas

Direcciones URL de entidades

Las direcciones URL de entidades las devuelve la interfaz getURL() y ofrecen a la infraestructura Elgg una forma común de dirigir a los usuarios a los manejadores de vistas apropiados para cualquier objeto.

Por ejemplo, una página de perfil en el caso de usuarios.

La dirección URL se define durante la función elgg\_register\_entity\_url\_handler(). La función que registre debe devolver la dirección URL apropiada para el tipo indicado, que puede ser una dirección configurada por un gestor de páginas.

El gestor predeterminado consiste en usar la interfaz de exportación predeterminada.

Entity loading performance

elgg_get_entities has a couple options that can sometimes be useful to improve performance.

  • preload_owners: If the entities fetched will be displayed in a list with the owner information, you can set this option to true to efficiently load the owner users of the fetched entities.
  • preload_containers: If the entities fetched will be displayed in a list using info from their containers, you can set this option to true to efficiently load them.
  • distinct: When Elgg fetches entities using an SQL query, Elgg must be sure that each entity row appears only once in the result set. By default it includes a DISTINCT modifier on the GUID column to enforce this, but some queries naturally return unique entities. Setting the distinct option to false will remove this modifier, and rely on the query to enforce its own uniqueness.

The internals of Elgg entity queries is a complex subject and it’s recommended to seek help on the Elgg Community site before using the distinct option.

Notas sobre versiones anteriores a la 1.8

update_subtype(): Esta función se introdujo en la versión 1.8. En versiones anteriores era necesario editar la base de datos manualmente en caso de haber cambiado el nombre de la clase asociada con un subtipo concreto.

elgg_register_entity_url_handler(): Esta función se introdujo en la versión 1.8. Esta nueva función substituye a register_entity_url_handler(), ahora obsoleta. Use la función vieja sólo para versiones de Elgg anteriores a la 1.8.

elgg_get_entities_from_metadata(): This function is new in 1.8. It deprecates get_entities_from_metadata(), which you should use if developing for a pre-1.8 version of Elgg.

Custom database functionality

It is strongly recommended to use entities wherever possible. However, Elgg supports custom SQL queries using the database API.

Example: Run SQL script on plugin activation

This example shows how you can populate your database on plugin activation.

my_plugin/activate.php:

if (!elgg_get_plugin_setting('database_version', 'my_plugin') {
    run_sql_script(__DIR__ . '/sql/activate.sql');
    elgg_set_plugin_setting('database_version', 1, 'my_plugin');
}

my_plugin/sql/activate.sql:

-- Create some table
CREATE TABLE prefix_custom_table(
    id INTEGER AUTO_INCREMENT,
    name VARCHAR(32),
    description VARCHAR(32),
    PRIMARY KEY (id)
);

-- Insert initial values for table
INSERT INTO prefix_custom_table (name, description)
VALUES ('Peter', 'Some guy'), ('Lisa', 'Some girl');

Note that Elgg execute statements through PHPs built-in functions and have limited support for comments. I.e. only single line comments are supported and must be prefixed by «– » or «# «. A comment must start at the very beginning of a line.

Systemlog

Nota

This section need some attention and will contain outdated information

The default Elgg system log is a simple way of recording what happens within an Elgg system. It’s viewable and searchable directly from the administration panel.

System log storage

A system log row is stored whenever an event concerning an object whose class implements the Loggable interface is triggered. ElggEntity and ElggExtender implement Loggable, so a system log row is created whenever an event is performed on all objects, users, groups, sites, metadata and annotations.

Common events include:

  • create
  • update
  • delete
  • login

Creating your own system log

There are some reasons why you might want to create your own system log. For example, you might need to store a full copy of entities when they are updated or deleted, for auditing purposes. You might also need to notify an administrator when certain types of events occur.

To do this, you can create a function that listens to all events for all types of object:

register_elgg_event_handler('all','all','your_function_name');

Your function can then be defined as:

function your_function_name($object, $event) {
   if ($object instanceof Loggable) {
      ...
   }
}

You can then use the extra methods defined by Loggable to extract the information you need.