Bump versions
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage.pm
1
2 package MooseX::Storage;
3 use Moose qw(confess);
4
5 use MooseX::Storage::Meta::Attribute::DoNotSerialize;
6 use String::RewritePrefix ();
7
8 our $VERSION   = '0.26';
9 our $AUTHORITY = 'cpan:STEVAN';
10
11 sub import {
12     my $pkg = caller();
13
14     return if $pkg eq 'main';
15
16     ($pkg->can('meta'))
17         || confess "This package can only be used in Moose based classes";
18
19     $pkg->meta->add_method('Storage' => __PACKAGE__->meta->find_method_by_name('_injected_storage_role_generator'));
20 }
21
22 my %HORRIBLE_GC_AVOIDANCE_HACK;
23
24 sub __expand_role {
25     my ($base, $value) = @_;
26
27     return unless defined $value;
28
29     if (ref $value) {
30         my ($class, $param, $no) = @$value;
31         confess "too many args in arrayref role declaration" if defined $no;
32
33         $class = __expand_role($base => $class);
34         Class::MOP::load_class($class);
35
36         my $role = $class->meta->generate_role(parameters => $param);
37
38         $HORRIBLE_GC_AVOIDANCE_HACK{ $role->name } = $role;
39         return $role->name;
40     } else {
41         my $role = scalar String::RewritePrefix->rewrite(
42             {
43                 ''  => "MooseX::Storage::$base\::",
44                 '=' => '',
45             },
46             $value,
47         );
48
49         Class::MOP::load_class($role);
50         return $role;
51     }
52 }
53
54 sub _injected_storage_role_generator {
55     my %params = @_;
56
57     $params{base} = '=MooseX::Storage::Basic' unless defined $params{base};
58
59     my @roles = __expand_role(Base => $params{base});
60
61     # NOTE:
62     # you don't have to have a format
63     # role, this just means you dont
64     # get anything other than pack/unpack
65     push @roles, __expand_role(Format => $params{format});
66
67     # NOTE:
68     # many IO roles don't make sense unless
69     # you have also have a format role chosen
70     # too, the exception being StorableFile
71     #
72     # NOTE:
73     # we dont need this code anymore, cause
74     # the role composition will catch it for
75     # us. This allows the StorableFile to work
76     #(exists $params{'format'})
77     #    || confess "You must specify a format role in order to use an IO role";
78     push @roles, __expand_role(IO => $params{io});
79
80     # Note:
81     # These traits alter the behaviour of the engine, the user can
82     # specify these per role-usage
83     for my $trait ( @{ $params{'traits'} ||= [] } ) {
84         push @roles, __expand_role(Traits => $trait);
85     }
86
87     return @roles;
88 }
89
90 1;
91
92 __END__
93
94 =pod
95
96 =head1 NAME
97
98 MooseX::Storage - A serialization framework for Moose classes
99
100 =head1 SYNOPSIS
101
102   package Point;
103   use Moose;
104   use MooseX::Storage;
105
106   our $VERSION = '0.01';
107
108   with Storage('format' => 'JSON', 'io' => 'File');
109
110   has 'x' => (is => 'rw', isa => 'Int');
111   has 'y' => (is => 'rw', isa => 'Int');
112
113   1;
114
115   my $p = Point->new(x => 10, y => 10);
116
117   ## methods to pack/unpack an
118   ## object in perl data structures
119
120   # pack the class into a hash
121   $p->pack(); # { __CLASS__ => 'Point-0.01', x => 10, y => 10 }
122
123   # unpack the hash into a class
124   my $p2 = Point->unpack({ __CLASS__ => 'Point-0.01', x => 10, y => 10 });
125
126   ## methods to freeze/thaw into
127   ## a specified serialization format
128   ## (in this case JSON)
129
130   # pack the class into a JSON string
131   $p->freeze(); # { "__CLASS__" : "Point-0.01", "x" : 10, "y" : 10 }
132
133   # unpack the JSON string into a class
134   my $p2 = Point->thaw('{ "__CLASS__" : "Point-0.01", "x" : 10, "y" : 10 }');
135
136   ## methods to load/store a class
137   ## on the file system
138
139   $p->store('my_point.json');
140
141   my $p2 = Point->load('my_point.json');
142
143 =head1 DESCRIPTION
144
145 MooseX::Storage is a serialization framework for Moose, it provides
146 a very flexible and highly pluggable way to serialize Moose classes
147 to a number of different formats and styles.
148
149 =head2 Important Note
150
151 This is still an early release of this module, so use with caution.
152 It's outward facing serialization API should be considered stable,
153 but I still reserve the right to make tweaks if I need too. Anything
154 beyond the basic pack/unpack, freeze/thaw and load/store should not
155 be relied on.
156
157 =head2 Levels of Serialization
158
159 There are 3 levels to the serialization, each of which builds upon
160 the other and each of which can be customized to the specific needs
161 of your class.
162
163 =over 4
164
165 =item B<base>
166
167 The first (base) level is C<pack> and C<unpack>. In this level the
168 class is serialized into a Perl HASH reference, it is tagged with the
169 class name and each instance attribute is stored. Very simple.
170
171 This level is not optional, it is the bare minumum that
172 MooseX::Storage provides and all other levels build on top of this.
173
174 See L<Moosex::Storage::Basic> for the fundamental implementation and
175 options to C<pack> and C<unpack>
176
177 =item B<format>
178
179 The second (format) level is C<freeze> and C<thaw>. In this level the
180 output of C<pack> is sent to C<freeze> or the output of C<thaw> is sent
181 to C<unpack>. This levels primary role is to convert to and from the
182 specific serialization format and Perl land.
183
184 This level is optional, if you don't want/need it, you don't have to
185 have it. You can just use C<pack>/C<unpack> instead.
186
187 =item B<io>
188
189 The third (io) level is C<load> and C<store>. In this level we are reading
190 and writing data to file/network/database/etc.
191
192 This level is also optional, in most cases it does require a C<format> role
193 to also be used, the expection being the C<StorableFile> role.
194
195 =back
196
197 =head2 Behaviour modifiers
198
199 The serialization behaviour can be changed by supplying C<traits>.
200 This can be done as follows:
201
202   use MooseX::Storage;
203   with Storage( traits => [Trait1, Trait2,...] );
204
205 The following traits are currently bundled with C<MooseX::Storage>:
206
207 =over 4
208
209 =item OnlyWhenBuilt
210
211 Only attributes that have been built (ie, where the predicate returns
212 'true') will be serialized. This avoids any potentially expensive computations.
213
214 See L<MooseX::Storage::Traits::OnlyWhenBuilt> for details.
215
216 =back
217
218 =head2 How we serialize
219
220 There are always limits to any serialization framework, there are just
221 some things which are really difficult to serialize properly and some
222 things which cannot be serialized at all.
223
224 =head2 What can be serialized?
225
226 Currently only numbers, string, ARRAY refs, HASH refs and other
227 MooseX::Storage enabled objects are supported.
228
229 With Array and Hash references the first level down is inspected and
230 any objects found are serialized/deserialized for you. We do not do
231 this recusively by default, however this feature may become an
232 option eventually.
233
234 The specific serialize/deserialize routine is determined by the
235 Moose type constraint a specific attribute has. In most cases subtypes
236 of the supported types are handled correctly, and there is a facility
237 for adding handlers for custom types as well. This will get documented
238 eventually, but it is currently still in development.
239
240 =head2 What can not be serialized?
241
242 We do not support CODE references yet, but this support might be added
243 in using B::Deparse or some other deep magic.
244
245 Scalar refs are not supported, mostly because there is no way to know
246 if the value being referenced will be there when the object is inflated.
247 I highly doubt will be ever support this in a general sense, but it
248 would be possible to add this yourself for a small specific case.
249
250 Circular references are specifically disallowed, however if you break
251 the cycles yourself then re-assemble them later you can get around this.
252 The reason we disallow circular refs is because they are not always supported
253 in all formats we use, and they tend to be very tricky to do for all
254 possible cases. It is almost always something you want to have tight control
255 over anyway.
256
257 =head1 CAVEAT
258
259 This is B<not> a persistence framework, changes to your object after
260 you load or store it will not be reflected in the stored class.
261
262 =head1 EXPORTS
263
264 =over 4
265
266 =item B<Storage (%options)>
267
268 This module will export the C<Storage> method will can be used to
269 load a specific set of MooseX::Storage roles to implement a specific
270 combination of features. It is meant to make things easier, but it
271 is by no means the only way. You can still compose your roles by
272 hand if you like.
273
274 By default, options are assumed to be short forms.  For example, this:
275
276   Storage(format => 'JSON');
277
278 ...will result in looking for MooseX::Storage::Format::JSON.  To use a role
279 that is not under the default namespace prefix, start with an equal sign:
280
281   Storage(format => '=My::Private::JSONFormat');
282
283 To use a parameterized role (for which, see L<MooseX::Role::Parameterized>) you
284 can pass an arrayref of the role name (in short or long form, as above) and its
285 parameters:
286
287   Storage(format => [ JSONpm => { json_opts => { pretty => 1 } } ]);
288
289 =back
290
291 =head1 METHODS
292
293 =over 4
294
295 =item B<import>
296
297 =back
298
299 =head2 Introspection
300
301 =over 4
302
303 =item B<meta>
304
305 =back
306
307 =head1 TODO
308
309 This module needs docs and probably a Cookbook of some kind as well.
310 This is an early release, so that is my excuse for now :)
311
312 For the time being, please read the tests and feel free to email me
313 if you have any questions. This module can also be discussed on IRC
314 in the #moose channel on irc.perl.org.
315
316 =head1 BUGS
317
318 All complex software has bugs lurking in it, and this module is no
319 exception. If you find a bug please either email me, or add the bug
320 to cpan-RT.
321
322 =head1 AUTHOR
323
324 Chris Prather E<lt>chris.prather@iinteractive.comE<gt>
325
326 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
327
328 Yuval Kogman E<lt>yuval.kogman@iinteractive.comE<gt>
329
330 =head1 COPYRIGHT AND LICENSE
331
332 Copyright 2007-2008 by Infinity Interactive, Inc.
333
334 L<http://www.iinteractive.com>
335
336 This library is free software; you can redistribute it and/or modify
337 it under the same terms as Perl itself.
338
339 =cut