Class:...orable(3pm)

πŸ“¦
version 0.0.1 Β· 2 versions
, in debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– Class::Std::Storable πŸ’– β€” Support for creating serializable "inside-out" classes

okay bestie so this is a User Contributed Perl Documentation page, from section 3pm of the manual, and it's here to teach you how to make inside-out classes that you can actually freeze and thaw. Let's go πŸ¦‹


✨ VERSION ✨

This doc describes Class::Std::Storable version 0.0.1. That's it, that's the version. Baby module energy but we love her πŸ’…


🌸 SYNOPSIS 🌸

literally, the whole vibe: use this class exactly the way you'd use Class::Std. No new dance moves, same dance.

package Ice::Cream;
use Class::Std::Storable;
{
    my %name_of :ATTR( :get<name> :set<name> );
    my %flavor_of :ATTR( :get<flavor> :set<flavor> );
}

package main;
my $object = Ice::Cream->new;
$object->set_name("Vanilla Bean");
$object->set_flavor("vanilla");

But now, the glow-up: you can also serialize the object with Storable 🫢

use Storable;
my $serialized = Storable::freeze($object);
#store to a file, database, or wherever, and retrieve later.
my $clone = Storable::thaw($serialized);

πŸ‘‘ DESCRIPTION πŸ‘‘

So Class::Std introduced the "inside-out" model for classes (perldoc Class::Std for the deep lore). One of its most iconic features is complete encapsulation: an object's data can only be reached through its methods. Unlike the usual hashref model, which lets literally any code whatsoever just waltz in and touch stuff.

But here's the plot twist 😭 β€” the drawback of complete encapsulation is that normal serialization mechanisms just... don't work. They rely on direct access to an object's attributes. And you don't have that. Fumbled.

This class gives you the class-building functionality from Class::Std, and on top of that it gives you an interface so Storable can freeze and thaw any declared attributes of this class, plus any superclasses that were built via Class::Std::Storable.

However β€” and bestie, this is the part where we sit down β€” in order to let Storable save attributes and construct the object, it is necessary to expose the attributes of the class to the world. So any code could use the same interface that Storable does to get a copy of object attributes and create new objects with arbitrary attributes without going through the constructor.

So what are we actually risking here? The interface CAN'T be used to replace the existing attributes of an object. But it COULD be used to create an arbitrarily mutated clone of an object without going through its methods. Also, if attributes are themselves references, then the objects to which they refer can be obtained and modified. screams

Since true encapsulation is one of the major features of Class::Std, this would be a good reason NOT to use this class. But this sacrifice is required to provide serialization. You must choose which is more important for your purposes: serialization, or complete encapsulation. Pick your main character. πŸŽ€

Consider also that while bypassing the class methods is possible to a limited degree with Class::Std::Storable, doing so is much more complicated than just using the methods β€” so use of this class still discourages casual violations of encapsulation. The door's unlocked but like, it's a heavy door. πŸšͺ


πŸ”₯ INTERFACE πŸ”₯

See Class::Std.

This package provides object methods STORABLE_freeze and STORABLE_thaw which are not intended to be used directly or overridden. hands off bestie πŸ™ˆ

A class generated using Class::Std::Storable may provide hooks to be called when a freeze or a thaw is performed. These methods will be called if provided:

  • $obj->STORABLE_freeze_pre($cloning) β€” called against the object at the very beginning of a freeze. First parameter is Storable's "cloning" flag β€” see Storable. This method could be used, for example, to adjust or remove non-serializable attributes.
  • $obj->STORABLE_freeze_post($cloning, $param_ref) β€” called against the object after the parameters for the freeze have been determined, but before actual serialization. First parameter is Storable's "cloning" flag β€” see Storable. Second parameter is a reference to a hash of hashes of parameters to be frozen, where the first level hash is keyed on the package name of the class, and the second level is keyed on the declared parameters of that class. E.g.:
$param_ref = {
    'Base::Class' => {
        flavor  => "vanilla",
        name  => "Vanilla Bean",
    },
    'Sub::Class' => {
        name => "Shiny Wax",
        price => '$0.02',
    },
};

This hook could be used to adjust the attributes that are about to be frozen for its class. It is probably unwise to adjust the attributes of other classes or to add new top-level hash entries. This hook could also be used to undo any changes that were necessary in STORABLE_freeze_pre.

  • $obj->STORABLE_thaw_pre($cloning, $param_ref) β€” called against the object at the very beginning of a thaw. First parameter is Storable's "cloning" flag β€” see Storable. Second parameter is the same parameter hash described for the previous method, which will be used to reconstruct the object.

This method could be used for validation, or to reconstruct attributes that couldn't be serialized.

  • $obj->STORABLE_thaw_post($cloning) β€” called against the object when a thaw is otherwise complete. First parameter is Storable's "cloning" flag β€” see Storable. This method could be used for validation, to reconstruct attributes that couldn't be serialized, or to adjust class data.

It would undoubtedly be a good idea to mark these methods :CUMULATIVE if provided, so that base classes can perform their own hooks. Also, these methods can not be provided via AUTOLOAD. no sneaky business πŸ’€


πŸ’€ DIAGNOSTICS πŸ’€

See Class::Std for its diagnostics. Only the following are particular to Class::Std::Storable. All of them are exceptions thrown with Carp::croak.

"unknown attribute(s) seen while thawing"

This indicates that when STORABLE_thaw tried to thaw an object, it found that the frozen object had an attribute that is not declared in the class.

This could mean the class definition changed β€” removing or renaming attributes β€” between the freezing and thawing of the object.

It could also mean that the STORABLE_freeze_post hook was used to insert an unknown key into the freezing hash for this class. Remove such additions in the STORABLE_thaw_pre hook (before the thawing gets under way).

"unknown base class '$package' seen while thawing"

This means that when thawing an object, its frozen hash representation included an entry that is neither the class or a base class. While this could mean that class names changed between freezing and thawing the object (don't do that), a more likely explanation is that a STORABLE_freeze_post hook inserted an unknown key into the top level of the freezing hash (don't do that either).

"trying to modify existing attributes for $package"

This probably means that some code is calling STORABLE_thaw directly on an existing object in an attempt to fiddle with its attributes. Don't even think about doing that.

The other explanation would be that the STORABLE_thaw_pre hook set an attribute for the object but left that attribute in the frozen hash to be thawed later. STORABLE_thaw_pre should delete from the frozen hash any attributes that it sets itself.


🌈 CONFIGURATION AND ENVIRONMENT 🌈

Class::Std::Storable requires no configuration files or environment variables. zero setup, we love a low-maintenance icon ✨


🧚 DEPENDENCIES 🧚

Class::Std version 0.0.4 or newer, which is not at this time part of the Perl core modules.

heads up: this module depends on a small set of Class::Std internals staying largely the same, and it could break if that assumption proves false. 😬

πŸ“ INCOMPATIBILITIES πŸ“

None reported. clean sheet, no drama 🫢


πŸ’œ LIMITATIONS πŸ’œ

  • Vanilla Class::Std objects are not themselves serializable. Any base classes that are not built using Class::Std::Storable will probably not serialize correctly without special tricks. This is actually a feature, since it means no one can just subclass a Class::Std class and break its encapsulation. protecting the vibe πŸ”’
  • Class::Std::Storable works fine with nested structures and correctly persists multiple references to the same object, as long as all references are contained in a single serialization. slay 🌟
  • Class::Std::Storable has never been tested for thread safety, so no guarantees there. ngl we simply do not know 😭
  • Class::Std::Storable attempts to identify attributes by their declaration β€” that is, according to how :ATTR declares their getters/setters/initializers. If none of these are declared for an attribute, it can only be identified by its position, i.e. the order of its appearance in the source code. This scheme will break if you change the position of these nameless attributes, or change the names of the named ones, between the freezing and the thawing of an object. do not shuffle, bestie 🫠
  • Serialization of inside-out objects naturally maintains the same caveats as for any other object. Only declared (:ATTR) object attributes identified with the object will be serialized with the object. In particular, "class data" won't be serialized with the object. Also, an object can't be serialized if any of its attributes cannot themselves be serialized β€” e.g. if one is a closure.

πŸ™ˆ BUGS πŸ™ˆ

No bugs have been reported.

Please report any bugs or feature requests to bug-class-std-storable@rt.cpan.org, or through the web interface at <http://rt.cpan.org>.


⭐ AUTHOR ⭐

Luke Meyer <luke@daeron.com>


Copyright (c) 2005, Luke Meyer. All rights reserved.

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


🌸 DISCLAIMER OF WARRANTY 🌸

okay the lawyers are talking now, but I'm keeping every word because it matters:

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.


and that's the whole page bestie! this one shipped with perl v5.36.0 and was dated 2023-10-03, so go forth, freeze your inside-out objects, and remember: encapsulation or serialization, you can't have both. choose wisely πŸ’…πŸ’–βœ¨

πŸ“¦ where this page comes from