NAME
MooseX::Extended::Manual::Cloning - An overview of MooseX::Extended optional attribute cloning
VERSION
version 0.20
CLONING SUPPORT
MooseX::Extended
offers optional, EXPERIMENTAL support for attribute cloning, but differently from how we see it typically done. You can just pass the clone => 1
argument to your attribute and it will be cloned with Storable's dclone
function every time you read or write that attribute, it will be cloned if it's a reference, ensuring that your object is effectively immutable.
If you prefer, you can also pass a code reference or the name of a method you will use to clone the object. Each will receive three arguments: $self, $attribute_name, $value_to_clone
. Here's a full example, taken from our test suite.
package My::Class {
use MooseX::Extended types => [qw(NonEmptyStr HashRef InstanceOf)];
param name => ( isa => NonEmptyStr );
param payload => (
isa => HashRef,
clone => 1, # uses Storable::dclone
writer => 1,
);
param start_date => (
isa => InstanceOf ['DateTime'],
clone => sub ( $self, $name, $value ) {
return $value->clone;
},
);
param end_date => (
isa => InstanceOf ['DateTime'],
clone => '_clone_end_date',
);
sub _clone_end_date ( $self, $name, $value ) {
return $value->clone;
}
sub BUILD ( $self, @ ) {
if ( $self->end_date < $self->start_date ) {
croak("End date must not be before start date");
}
}
}
Warning: Be aware that this is a very useful technique, but cloning can be very expensive. If you have performance issues, profile your code and see if removing the safety of cloning can help.
AUTHOR
Curtis "Ovid" Poe <curtis.poe@gmail.com>
COPYRIGHT AND LICENSE
This software is Copyright (c) 2022 by Curtis "Ovid" Poe.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)