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