* implement the unpack( $data, inject => {...} ) feature.
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Basic.pm
1 package MooseX::Storage::Basic;
2 use Moose::Role;
3
4 use MooseX::Storage::Engine;
5
6 our $VERSION   = '0.18';
7 our $AUTHORITY = 'cpan:STEVAN';
8
9 sub pack {
10     my ( $self, @args ) = @_;
11     my $e = $self->_storage_get_engine( object => $self );
12     $e->collapse_object(@args);
13 }
14
15 sub unpack {
16     my ($class, $data, %args) = @_;
17     my $e = $class->_storage_get_engine(class => $class);
18     
19     $class->_storage_construct_instance( 
20         $e->expand_object($data, %args), 
21         \%args 
22     );
23 }
24
25 sub _storage_get_engine {
26     my $self = shift;
27     MooseX::Storage::Engine->new( @_ );
28 }
29
30 sub _storage_construct_instance {
31     my ($class, $args, $opts) = @_;
32     my %i = defined $opts->{'inject'} ? %{ $opts->{'inject'} } : ();
33  
34     $class->new( %$args, %i );
35 }
36
37 1;
38
39 __END__
40
41 =pod
42
43 =head1 NAME
44
45 MooseX::Storage::Basic - The simplest level of serialization
46
47 =head1 SYNOPSIS
48
49   package Point;
50   use Moose;
51   use MooseX::Storage;
52   
53   our $VERSION = '0.01';
54   
55   with Storage;
56   
57   has 'x' => (is => 'rw', isa => 'Int');
58   has 'y' => (is => 'rw', isa => 'Int');
59   
60   1;
61   
62   my $p = Point->new(x => 10, y => 10);
63   
64   ## methods to pack/unpack an 
65   ## object in perl data structures
66   
67   # pack the class into a hash
68   $p->pack(); # { __CLASS__ => 'Point-0.01', x => 10, y => 10 }
69   
70   # unpack the hash into a class
71   my $p2 = Point->unpack({ __CLASS__ => 'Point-0.01', x => 10, y => 10 });
72   
73   # unpack the hash, with insertion of paramaters
74   my $p3 = Point->unpack( $p->pack, inject => { x => 11 } );
75
76 =head1 DESCRIPTION
77
78 This is the most basic form of serialization. This is used by default 
79 but the exported C<Storage> function.
80
81 =head1 METHODS
82
83 =over 4
84
85 =item B<pack>
86
87 =item B<unpack ($data [, insert => { key => val, ... } ] )>
88
89 Providing the C<insert> argument let's you supply additional arguments to
90 the class' C<new> function, or override ones from the serialized data.
91
92 =back
93
94 =head2 Introspection
95
96 =over 4
97
98 =item B<meta>
99
100 =back
101
102 =head1 BUGS
103
104 All complex software has bugs lurking in it, and this module is no 
105 exception. If you find a bug please either email me, or add the bug
106 to cpan-RT.
107
108 =head1 AUTHOR
109
110 Chris Prather E<lt>chris.prather@iinteractive.comE<gt>
111
112 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
113
114 =head1 COPYRIGHT AND LICENSE
115
116 Copyright 2007-2008 by Infinity Interactive, Inc.
117
118 L<http://www.iinteractive.com>
119
120 This library is free software; you can redistribute it and/or modify
121 it under the same terms as Perl itself.
122
123 =cut