The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Class::Attribute - A fast and light weight alternative for defining class attributes.

VERSION

Version 0.024

SYNOPSIS

This is a very light weight and fast implementation for defining attributes without having to resort to full blown use of Moose.

The module tries to fill in gaps found in several other similar implementations found on CPAN; Class::Accessor, Class::InsideOut, Object::InsideOut, Moose and Mouse.

Class::Attribute,

1. Allows definition of attributes of the following type/permissions.

    a. public
    b. private
    c. protected
    d. readonly

2. Has a very simple and extensible attribute validation mechanism using regular expressions.

3. Can set default values for attributes.

    # example

    package MyUser;

    use DateTime;
    use YAML;
    # exports symbols into the MyUser namespace and then
    # pushes itself into @MyUser::ISA.
    use Class::Attribute;

    attribute 'id',      is_int, protected, public_accessor, default => 1;
    attribute 'name',    is_string(10, 40, 'a name of 10 - 40 chars');
    attribute 'sex',     is_in( ['M', 'F'], 'sex (M/F)' ), private;
    attribute 'age',     is_int, default => 18;
    attribute 'email',   is_email, predicate => 'has_email';
    attribute 'dob',     is_date;
    attribute 'updated', isa => 'DateTime', default => sub { DateTime->now };

    sub new {
        my $self = shift->SUPER::new(@_);
        my %args = @_;
        $self->set_sex($args{sex}) if exists $args{sex};

        return $self;
    }

    sub serialize {
        my ($self) = @_;
        if ($self->is_updated) {
            $self->set_id(time) unless defined $self->get_id;
            $self->set_updated(DateTime->now);
            my %attrs = $self->_get_all_attributes;
            return Dump(\%attrs);
        }
    }

    1;

    # and now in your script ...

    use MyUser;
    my $user = MyUser->new(sex => 'M');

    # should return FALSE.
    print $user->has_email;

    $user->set_name('foo bar baz');
    $user->set_email('foo@bar.com');

    # should return TRUE.
    print $user->has_email;

    # should return 18.
    print $user->get_age, "\n";

    $user->set_age('2008-123-1');
    # returns validation errors.
    my @errors = $user->validate;

    # should throw a permission error.
    $user->set_id(1);

    # should serialize the fields including ones set by default.
    print $user->serialize, "\n";

EXPORT

attribute, public, private, protected, readonly, public_accessor, protected_accessor, private_accessor, public_mutator, protected_mutator, private_mutator, is_int, is_float, is_email, is_boolean, is_string, is_date, is_datetime, is_in

FUNCTIONS

import

This is where all the initial compile time work happens. All this does is pushes some of the useful symbols to the caller namespace. Read EXPORT section for the list of exported symbols.

new

The default constructor. It calls _new() which sets the default values and returns a blessed reference. Override this in your class if you want the constructor to do more with the provided arguments like setting protected attributes etc.

_new

Sets the default values as defined.

attr

Same as attribute(), read below.

attribute

This basically does the grunt work of parsing the attribute definitions, defaults etc and setting up appropriate methods in the caller namespace.

The possible attribute definitions are explained below.

1. Attribute Permission. This can be defined for accessors and mutators as public (default), private, protected or readonly or for finer grain control separately as public_accessor, public_mutator, protected_accessor, protected_mutator, private_accessor or private_mutator.

 # e.g.  attribute 'id1', public;
 # e.g.  attribute 'id2', private, protected_accessor;
 # e.g.  attribute 'id3', protected;
 # e.g.  attribute 'id4', readonly;

CAVEATS

The readonly attribute definition will result in a public accessor and private mutator.

2. Attribute ISA - Checks the value in the validator if it is an instance of a particular class.

 # e.g.  attribute 'dob', public, isa => 'DateTime';

3. Attribute Default - Any scalar value or CODEREF that will be assigned by default in the constructor.

 # e.g.  attribute 'age', public, default => 18;

4. Attribute Validation - A reference to an array with 2 elements. The first one should be a regular expression and the second an explanation what the validation does.

 # e.g.  attribute 'dob', public, like => [qr/^\d{4}-\d\d-\d\d$/, 'a date of the form YYYY-MM-DD'];

The following validators are exported as functions into the caller namespace.

 is_int, is_float, is_boolean, is_email, is_string, is_in, is_date, is_datetime

5. Attribute Predicate - A method name that is created to check if the attribute value has been set or instantiated.

 # e.g.  attribute 'email', public, predicate => 'has_email';

validate

validates the attributes against any specified validators and returns failures if any.

_get_all_attributes

This is a private method that returns a hash of attribute names and their values.

is_string($min_len, $max_len, $comment)

A validator that accepts 3 arguments (min length, max length, comment) and returns a hash that Class::Attribute likes. All parameters are optional.

is_in($list_ref, $comment)

A validator that checks if an attribute is an element of a provided set of values.

AUTHOR

Bharanee Rathna, <deepfryed a la gmail>

BUGS

Please report any bugs or feature requests to bug-class-attribute at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Class-Attribute. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Class::Attribute

You can also look for information at:

ACKNOWLEDGEMENTS

Thanks to Class::Accessor for all the pain it's saved me from in the past. Thanks to Moose for doing what should have been in Perl CORE looooooong back.

COPYRIGHT & LICENSE

Copyright 2009 Bharanee Rathna, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.