| 1 | |||
| 2 | =head1 NAME | ||
| 3 | |||
| 4 | Util::DataThing::Serializer - Abstract base class for objects that can serialize and deserialize Util::DataThing objects to various formats | ||
| 5 | |||
| 6 | =head1 SYNOPSIS | ||
| 7 | |||
| 8 | my $serializer = Util::DataThing::Serializer::SomeSubclass->new(); | ||
| 9 | $serializer->serialize_object_to_stream($object, $fh); | ||
| 10 | |||
| 11 | =cut | ||
| 12 | |||
| 13 | package Util::DataThing::Serializer::JSON; | ||
| 14 | |||
| 15 | use strict; | ||
| 16 | use warnings; | ||
| 17 | use Carp; | ||
| 18 | |||
| 19 | sub serialize_object_to_string { | ||
| 20 | Carp::croak("$_[0] does not implement serialize_object_to_string"); | ||
| 21 | } | ||
| 22 | |||
| 23 | sub deserialize_object_from_string { | ||
| 24 | Carp::croak("$_[0] does not implement deserialize_object_from_string"); | ||
| 25 | } | ||
| 26 | |||
| 27 | sub serialize_object_to_stream { | ||
| 28 | my ($self, $object, $stream) = @_; | ||
| 29 | |||
| 30 | $stream->print($self->serialize_object_to_string($object)); | ||
| 31 | } | ||
| 32 | |||
| 33 | sub deserialize_object_from_stream { | ||
| 34 | my ($self, $stream, $class) = @_; | ||
| 35 | |||
| 36 | return $self->deserialize_object_from_string(join('', <$stream>), $class); | ||
| 37 | } | ||
| 38 | |||
| 39 | =head1 METHODS | ||
| 40 | |||
| 41 | =head2 $string = $serializer->serialize_object_to_string($object) | ||
| 42 | |||
| 43 | Serializes the given L<Util::DataThing> object to a string and returns that string. | ||
| 44 | |||
| 45 | =head2 $object = $serializer->deserialize_object_from_string($string, $class) | ||
| 46 | |||
| 47 | Attempts to deserialize the given string to an object of the given | ||
| 48 | class, which must be a subclass of L<Util::DataThing>. | ||
| 49 | |||
| 50 | =head2 $serializer->serialize_object_to_stream($object, $stream) | ||
| 51 | |||
| 52 | Serializes the given L<Util::DataThing> object to a string and writes | ||
| 53 | the result to the given stream. | ||
| 54 | |||
| 55 | The stream must be some kind of L<IO> object. | ||
| 56 | |||
| 57 | =head2 $object = $serializer->deserialize_object_from_stream($stream, $class) | ||
| 58 | |||
| 59 | Attempts to deserialize data read from the given stream to an object of the given | ||
| 60 | class, which must be a subclass of L<Util::DataThing>. | ||
| 61 | |||
| 62 | The stream must be some kind of L<IO> object. | ||
| 63 | |||
| 64 | =head1 INFORMATION FOR SUBCLASS IMPLEMENTORS | ||
| 65 | |||
| 66 | If you are developing a subclass of this class, you must provide implementations | ||
| 67 | for the serialize and deserialize functions based on strings. | ||
| 68 | |||
| 69 | Default implementations of the stream-based methods are provided which are | ||
| 70 | simple wrappers around the string-based methods. Subclasses should | ||
| 71 | override these if they are able to do something more sensible. | ||
| 72 | |||
| 73 | =cut | ||
| 74 | |||
| 75 | 1; |