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

Kelp::Base - Simple lazy attributes

SYNOPSIS

    use Kelp::Base;

    attr source => 'dbi:mysql:users';
    attr user   => 'test';
    attr pass   => 'secret';
    attr opts   =>  sub { { PrintError => 1, RaiseError => 1 } };

    attr dbh => sub {
        my $self = shift;
        DBI->connect( $self->sourse, $self->user, $self->pass, $self->opts );
    };

    # Later ...
    sub do_stuff {
        my $self = shift;
        $self->dbh->do('DELETE FROM accounts');
    }

or

    use Kelp::Base 'Module::Name';    # Extend Module::Name

or

    use Kelp::Base -strict;    # Only use strict, warnings and v5.10
                                  # No magic

DESCRIPTION

This module provides simple lazy attributes.

WHY?

Some users will naturally want to ask "Why not use Moose/Mouse/Moo/Mo?". The answer is that the Kelp web framework needs lazy attributes, but the author wanted to keep the code light and object manager agnostic. This allows the users of the framework to choose an object manager to their liking. As a nice addition, our getters and constructors are quite a bit faster than any non-XS variant of Moose, which makes the core code very fast.

There is nothing more annoying than a module that forces you to use Moose when you are perfectly fine with Moo or Mo, for example. Since this module is so minimal, you should probably switch to a full-blown OO system of your choice when writing your application. Kelp::Base should be compatible with it as long as it uses blessed hashes under the hood.

USAGE

    use Kelp::Base;

The above will automatically include strict, warnings and v5.10. It will also inject a new sub in the current class called attr.

    attr name1 => 1;                      # Fixed value
    attr name2 => sub { [ 1, 2, 3 ] };    # Array
    attr name3 => sub {
        $_[0]->other;
      }

    ...

    say $self->name1;               # 1
    $self->name2( [ 6, 7, 8 ] );    # Set new value

All those attributes will be available for reading and writing in each instance of the current class. If you want to create a read-only attribute, prefix its name with a dash.

    attr -readonly => "something";

    # Later
    say $self->readonly;           # something
    $self->readonly("nothing");    # no change

Kelp::Base can also be imported without turning an object into a class:

    # imports strict, warnings and :5.10
    use Kelp::Base -strict;

    # imports all of the above plus attr
    use Kelp::Base -attr;

The former is useful for less boilerplate in scripts on older perls. The latter is useful when using attr with Role::Tiny.

SEE ALSO

Kelp, Moose, Moo, Mo, Any::Moose