Skip to content

DevGuide ClassTaggable

Violet edited this page Nov 2, 2010 · 2 revisions

MDG: Building Taggable Objects

Melody comes with an easy to use tagging framework that allows any developer to attach tags to any object in the system. Once an object is designated as "taggable" then they will immediate be able to use all of the interface methods of a taggable object to get and set tags on that object.

Making an object taggable simply allows for the easy storage, retrieval and association of tags with an object. It has no bearing on the user interface, and it is up to the developer to implement any front end user interfaces for the manipulation of tag data.

The following methods are supported on any taggable object:

  • tags(@tags) - gets or sets an object's list of tags. If used as a set operation, this method will replace any existing tags with the ARRAY of provided tags.

  • add_tags(@tags) - takes as input an ARRAY of tags to append to an object

  • remove_tags(@tags) - removes any tags found in the ARRAY of tags provided to the method as inpput

  • has_tag($tag) - returns true if the specified tag can be found in the associated object

  • tag_count()- returns the number of tags this object has

  • tagged_count() - returns the number of objects that share the specified tag

Inheriting from the Taggable Interface

To make an object taggable, a developer need only state that their package inherits from the MT::Taggable interface like so:

package My::Object::Model;
use MT::Tag;
use base qw( MT::Object MT::Taggable );

Using the MT::Taggable Interface

Then you get the methods in the Taggable interface on your model objects:

sub tag_awesomely {
    my ($m_id) = @_;
    my $m = My::Object::Model->load($m_id);
    if (!$m->has_tags('awesome')) {
        $m->add_tags('awesome');
    }
    $m->save();  # tags are automatically saved by the
                 # MT::Taggable::post_save_tags callback
}

Setting Tags Using Tag Delimiters

Melody allows users to specify as a personal preference the delimiter they would like to use for separating on tag from another. The most common two delimiters being commas, or spaces. The code snippet below shows a simple recipe for setting the tags on an object while respecting a user's tag delimiter preference.

require MT::Tag;
my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
my @tags = MT->model('tag')->split( $tag_delim, $tags );
if (@tags) {
    $obj->set_tags(@tags);
}
else {
    $obj->remove_tags();
}

 


Questions, comments, can't find something? Let us know at our community outpost on Get Satisfaction.

Credits

  • Author: Byrne Reese
  • Edited by: Violet Bliss Dietz
Clone this wiki locally