Skip to content

Add support for lazy builders - #14

Open
tobyink wants to merge 2 commits into
tsee:masterfrom
tobyink:master
Open

Add support for lazy builders#14
tobyink wants to merge 2 commits into
tsee:masterfrom
tobyink:master

Conversation

@tobyink

@tobyink tobyink commented Dec 5, 2025

Copy link
Copy Markdown
Contributor

This commit adds support for lazy builders:

use v5.12;

package Foo {
  use Class::XSAccessor
    constructor  => 'new',
    lazy_getters => { get_bar => 'bar' };

  sub _build_bar {
    my $self = shift;
    return 'iron bar';
  }
}

my $foo1 = Foo->new( bar => 'chocolate bar' );
say $foo1->get_bar;   # chocolate bar

my $foo2 = Foo->new;
say $foo2->get_bar;   # iron bar

When the lazy getter is called, if the hash key does not exist, a method called "build$slot" will be called to return a default value. This will be stored in the hash and then the getter will continue as normal.

Also lazy_accessors is supported, including support for chained => 1.

I think this patch could be very helpful for accelerating Moo-based code which tries to use Class::XSAccessor when possible, but currently cannot for any lazy-built attributes.

Dancer2 in particular makes heavy use of lazy-built attributes, so this patch has the potential to eventually speed up Dancer2-based websites.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant