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