~ubuntu-branches/ubuntu/intrepid/libclass-meta-perl/intrepid

« back to all changes in this revision

Viewing changes to lib/Class/Meta.pm

  • Committer: Bazaar Package Importer
  • Author(s): Krzysztof Krzyzaniak (eloy)
  • Date: 2006-01-03 17:29:20 UTC
  • Revision ID: james.westby@ubuntu.com-20060103172920-h94p8qrrav90bzq0
Tags: upstream-0.52
ImportĀ upstreamĀ versionĀ 0.52

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package Class::Meta;
 
2
 
 
3
# $Id: Meta.pm 2405 2005-12-17 03:41:09Z theory $
 
4
 
 
5
=head1 NAME
 
6
 
 
7
Class::Meta - Class automation, introspection, and data validation
 
8
 
 
9
=head1 SYNOPSIS
 
10
 
 
11
Generate a class:
 
12
 
 
13
  package MyApp::Thingy;
 
14
  use strict;
 
15
  use Class::Meta;
 
16
  use Class::Meta::Types::String;
 
17
  use Class::Meta::Types::Numeric;
 
18
 
 
19
  BEGIN {
 
20
      # Create a Class::Meta object for this class.
 
21
      my $cm = Class::Meta->new( key => 'thingy' );
 
22
 
 
23
      # Add a constructor.
 
24
      $cm->add_constructor( name   => 'new',
 
25
                            create => 1 );
 
26
 
 
27
      # Add a couple of attributes with generated methods.
 
28
      $cm->add_attribute( name     => 'id',
 
29
                          authz    => Class::Meta::READ,
 
30
                          type     => 'integer',
 
31
                          required => 1,
 
32
                          default  => sub { Data::UUID->new->create_str } );
 
33
      $cm->add_attribute( name     => 'name',
 
34
                          type     => 'string',
 
35
                          required => 1,
 
36
                          default  => undef );
 
37
      $cm->add_attribute( name     => 'age',
 
38
                          type     => 'integer',
 
39
                          default  => undef );
 
40
 
 
41
      # Add a custom method.
 
42
      $cm->add_method( name => 'chk_pass',
 
43
                       view => Class::Meta::PUBLIC );
 
44
      $cm->build;
 
45
  }
 
46
 
 
47
Then use the class:
 
48
 
 
49
  use MyApp::Thingy;
 
50
 
 
51
  my $thingy = MyApp::Thingy->new;
 
52
  print "ID: ", $thingy->id, $/;
 
53
  $thingy->name('Larry');
 
54
  print "Name: ", $thingy->name, $/;
 
55
  $thingy->age(42);
 
56
  print "Age: ", $thingy->age, $/;
 
57
 
 
58
Or make use of the introspection API:
 
59
 
 
60
  use MyApp::Thingy;
 
61
 
 
62
  my $class = MyApp::Thingy->my_class;
 
63
  my $thingy;
 
64
 
 
65
  print "Examining object of class ", $class->package, $/;
 
66
 
 
67
  print "\nConstructors:\n";
 
68
  for my $ctor ($class->constructors) {
 
69
      print "  o ", $ctor->name, $/;
 
70
      $thingy = $ctor->call($class->package);
 
71
  }
 
72
 
 
73
  print "\nAttributes:\n";
 
74
  for my $attr ($class->attributes) {
 
75
      print "  o ", $attr->name, " => ", $attr->get($thingy), $/;
 
76
      if ($attr->authz >= Class::Meta::SET && $attr->type eq 'string') {
 
77
          $attr->get($thingy, 'hey there!');
 
78
          print "    Changed to: ", $attr->get($thingy), $/;
 
79
      }
 
80
  }
 
81
 
 
82
  print "\nMethods:\n";
 
83
  for my $meth ($class->methods) {
 
84
      print "  o ", $meth->name, $/;
 
85
      $meth->call($thingy);
 
86
  }
 
87
 
 
88
=head1 DESCRIPTION
 
89
 
 
90
Class::Meta provides an interface for automating the creation of Perl classes
 
91
with attribute data type validation. It differs from other such modules in
 
92
that it includes an introspection API that can be used as a unified interface
 
93
for all Class::Meta-generated classes. In this sense, it is an implementation
 
94
of the "Facade" design pattern.
 
95
 
 
96
=head1 JUSTIFICATION
 
97
 
 
98
One might argue that there are already too many class automation and parameter
 
99
validation modules on CPAN. And one would be right. They range from simple
 
100
accessor generators, such as L<Class::Accessor|Class::Accessor>, to simple
 
101
parameter validators, such as L<Params::Validate|Params::Validate>, to more
 
102
comprehensive systems, such as L<Class::Contract|Class::Contract> and
 
103
L<Class::Tangram|Class::Tangram>. But, naturally, none of them could do
 
104
exactly what I needed.
 
105
 
 
106
What I needed was an implementation of the "Facade" design pattern. Okay, this
 
107
isn't a facade like the GOF meant it, but it is in the respect that it
 
108
creates classes with a common API so that objects of these classes can all be
 
109
used identically, calling the same methods on each. This is done via the
 
110
implementation of an introspection API. So the process of creating classes
 
111
with Class::Meta not only creates attributes and accessors, but also creates
 
112
objects that describe those classes. Using these descriptive objects, client
 
113
applications can determine what to do with objects of Class::Meta-generated
 
114
classes. This is particularly useful for user interface code.
 
115
 
 
116
=head1 USAGE
 
117
 
 
118
Before we get to the introspection API, let's take a look at how to create
 
119
classes with Class::Meta. Unlike many class automation modules for Perl, the
 
120
classes that Class::Meta builds do not inherit from Class::Meta. This frees
 
121
you from any dependencies on the interfaces that such a base class might
 
122
compel. For example, you can create whatever constructors you like, and name
 
123
them whatever you like.
 
124
 
 
125
I recommend that you create your Class::Meta classes in a C<BEGIN>
 
126
block. Although this is not strictly necessary, it helps to ensure that the
 
127
classes you're building are completely constructed and ready to go by the time
 
128
compilation has completed. Creating classes with Class::Meta is easy, using
 
129
the Class::Meta object oriented interface. Here is an example of a very simple
 
130
class:
 
131
 
 
132
  package MyApp::Dog;
 
133
  use strict;
 
134
  use Class::Meta;
 
135
  use Class::Meta::Types::Perl;
 
136
 
 
137
  BEGIN {
 
138
      # Create a Class::Meta object for this class.
 
139
      my $cm = Class::Meta->new( key => 'dog' );
 
140
 
 
141
      # Add a constructor.
 
142
      $cm->add_constructor( name   => 'new',
 
143
                            create => 1 );
 
144
 
 
145
      # Add an attribute.
 
146
      $cm->add_attribute( name   => 'tail',
 
147
                          type   => 'scalar' );
 
148
 
 
149
      # Add a custom method.
 
150
      $cm->add_method( name => 'wag' );
 
151
      $cm->build;
 
152
  }
 
153
 
 
154
  sub wag {
 
155
      my $self = shift;
 
156
      print "Wagging ", $self->tail;
 
157
  }
 
158
 
 
159
This simple example shows of the construction of all three types of objects
 
160
supported by Class::Meta: constructors, attributes, and methods. Here's how
 
161
it does it:
 
162
 
 
163
=over 4
 
164
 
 
165
=item *
 
166
 
 
167
First we load Class::Meta and Class::Meta::Types::Perl. The latter module
 
168
creates data types that can be used for attributes, including a "scalar"
 
169
data type.
 
170
 
 
171
=item *
 
172
 
 
173
Second, we create a Class::Meta object. It's okay to create it within the
 
174
C<BEGIN> block, as it won't be needed beyond that. All Class::Meta classes
 
175
have a C<key> that uniquely identifies them across an application. If none is
 
176
provided, the class name will be used, instead.
 
177
 
 
178
=item *
 
179
 
 
180
Next, we create a Class::Meta::Constructor object to describe a constructor
 
181
method for the class. The C<create> parameter to the C<add_constructor()> method
 
182
tells Class::Meta to create the constructor named "C<new()>".
 
183
 
 
184
=item *
 
185
 
 
186
Then we call C<add_attribute()> to create a single attribute, "tail". This is a
 
187
simple scalar attribute, meaning that any scalar value can be stored in
 
188
it. Class::Meta will create a Class::Meta::Attribute object that describes
 
189
this attribute, and will also shortly create accessor methods for the
 
190
attribute.
 
191
 
 
192
=item *
 
193
 
 
194
The C<add_method()> method constructs a Class::Meta::Method object to describe
 
195
any methods written for the class. In this case, we've told Class::Meta that
 
196
there will be a C<wag()> method.
 
197
 
 
198
=item *
 
199
 
 
200
And finally, we tell Class::Meta to build the class. This is the point at
 
201
which all constructors and accessor methods will be created in the class. In
 
202
this case, these include the C<new()> constructor and a C<tail()> accessor for
 
203
the "tail" attribute. And finally, Class::Meta will install another method,
 
204
C<my_class()>. This method will return a Class::Meta::Class object that
 
205
describes the class, and provides the complete introspection API.
 
206
 
 
207
=back
 
208
 
 
209
Thus, the class the above code creates has this interface:
 
210
 
 
211
  sub my_class;
 
212
  sub new;
 
213
  sub tail;
 
214
  sub wag;
 
215
 
 
216
=head2 Data Types
 
217
 
 
218
By default, Class::Meta loads no data types. If you attempt to create an
 
219
attribute without creating or loading the appropriate data type, you will
 
220
get an error.
 
221
 
 
222
But I didn't want to leave you out in the cold, so I created a whole bunch of
 
223
data types to get you started. They can be loaded simply by creating the
 
224
appropriate module. The modules are:
 
225
 
 
226
=over 4
 
227
 
 
228
=item L<Class::Meta::Types::Perl|Class::Meta::Types::Perl>
 
229
 
 
230
Typical Perl data types.
 
231
 
 
232
=over 4
 
233
 
 
234
=item scalar
 
235
 
 
236
Any scalar value.
 
237
 
 
238
=item scalarref
 
239
 
 
240
A scalar reference.
 
241
 
 
242
=item array
 
243
 
 
244
=item arrayref
 
245
 
 
246
An array reference.
 
247
 
 
248
=item hash
 
249
 
 
250
=item hashref
 
251
 
 
252
A hash reference.
 
253
 
 
254
=item code
 
255
 
 
256
=item coderef
 
257
 
 
258
=item closure
 
259
 
 
260
A code reference.
 
261
 
 
262
=back
 
263
 
 
264
=item L<Class::Meta::Types::String|Class::Meta::Types::String>
 
265
 
 
266
=over 4
 
267
 
 
268
=item string
 
269
 
 
270
Attributes of this type must contain a string value. Essentially, this means
 
271
anything other than a reference.
 
272
 
 
273
=back
 
274
 
 
275
=item L<Class::Meta::Types::Boolean|Class::Meta::Types::Boolean>
 
276
 
 
277
=over 4
 
278
 
 
279
=item boolean
 
280
 
 
281
=item bool
 
282
 
 
283
Attributes of this type store a boolean value. Implementation-wise, this means
 
284
either a 1 or a 0.
 
285
 
 
286
=back
 
287
 
 
288
=item L<Class::Meta::Types::Numeric|Class::Meta::Types::Numeric>
 
289
 
 
290
These data types are validated by the functions provided by
 
291
L<Data::Types|Data::Types>.
 
292
 
 
293
=over 4
 
294
 
 
295
=item whole
 
296
 
 
297
A whole number.
 
298
 
 
299
=item integer
 
300
 
 
301
An integer.
 
302
 
 
303
=item decimal
 
304
 
 
305
A decimal number.
 
306
 
 
307
=item real
 
308
 
 
309
A real number.
 
310
 
 
311
=item float
 
312
 
 
313
a floating point number.
 
314
 
 
315
=back
 
316
 
 
317
=back
 
318
 
 
319
Other data types may be added in the future. See the individual data type
 
320
modules for more information.
 
321
 
 
322
=head2 Accessors
 
323
 
 
324
Class::Meta supports the creation of three different types of attribute
 
325
accessors: typical Perl single-method accessors, "affordance" accessors, and
 
326
"semi-affordance" accessors. The single accessors are named for their
 
327
attributes, and typically tend to look like this:
 
328
 
 
329
  sub tail {
 
330
      my $self = shift;
 
331
      return $self->{tail} unless @_;
 
332
      return $self->{tail} = shift;
 
333
  }
 
334
 
 
335
Although this can be an oversimplification if the data type has associated
 
336
validation checks.
 
337
 
 
338
Affordance accessors provide at up to two accessors for every attribute: One
 
339
to set the value and one to retrieve the value. They tend to look like this:
 
340
 
 
341
  sub get_tail { shift->{tail} }
 
342
 
 
343
  sub set_tail { shift->{tail} = shift }
 
344
 
 
345
These accessors offer a bit less overhead than the traditional Perl accessors,
 
346
in that they don't have to check whether they're called to get or set a
 
347
value. They also have the benefit of creating a psychological barrier to
 
348
misuse. Since traditional Perl accessors I<can> be created as read-only or
 
349
write-only accessors, one can't tell just by looking at them which is the
 
350
case. The affordance accessors make this point moot, as they make clear what
 
351
their purpose is.
 
352
 
 
353
Semi-affordance accessors are similar to affordance accessors in that they
 
354
provide at least two accessors for every attribute. However, the accessor that
 
355
fetches the value is named for the attribute. Thus, they tend to look like
 
356
this:
 
357
 
 
358
  sub tail { shift->{tail} }
 
359
 
 
360
  sub set_tail { shift->{tail} = shift }
 
361
 
 
362
To get Class::Meta's data types to create affordance accessors, simply pass
 
363
the string "affordance" to them when you load them:
 
364
 
 
365
  use Class::Meta::Types::Perl 'affordance';
 
366
 
 
367
Likewise, to get them to create semi-affordance accessors, pass the string
 
368
"semi-affordance":
 
369
 
 
370
  use Class::Meta::Types::Perl 'semi-affordance';
 
371
 
 
372
The boolean data type is the only one that uses a slightly different approach
 
373
to the creation of affordance accessors: It creates three of them. Assuming
 
374
you're creating a boolean attribute named "alive", it will create these
 
375
accessors:
 
376
 
 
377
  sub is_alive      { shift->{alive} }
 
378
  sub set_alive_on  { shift->{alive} = 1 }
 
379
  sub set_alive_off { shift->{alive} = 0 }
 
380
 
 
381
Incidentally, I stole the term "affordance" from Damian Conway's "Object
 
382
Oriented Perl," pp 83-84, where he borrows it from Donald Norman.
 
383
 
 
384
See L<Class::Meta::Type|Class::Meta::Type> for details on creating new data
 
385
types.
 
386
 
 
387
=head2 Introspection API
 
388
 
 
389
Class::Meta provides four classes the make up the introspection API for
 
390
Class::Meta-generated classes. Those classes are:
 
391
 
 
392
=head3 L<Class::Meta::Class|Class::Meta::Class>
 
393
 
 
394
Describes the class. Each Class::Meta-generated class has a single constructor
 
395
object that can be retrieved by calling a class' C<my_class()> class
 
396
method. Using the Class::Meta::Class object, you can get access to all of the
 
397
other objects that describe the class. The relevant methods are:
 
398
 
 
399
=over 4
 
400
 
 
401
=item constructors
 
402
 
 
403
Provides access to all of the Class::Meta::Constructor objects that describe
 
404
the class' constructors, and provide indirect access to those constructors.
 
405
 
 
406
=item attributes
 
407
 
 
408
Provides access to all of the Class::Meta::Attribute objects that describe the
 
409
class' attributes, and provide methods for indirectly getting and setting
 
410
their values.
 
411
 
 
412
=item methods
 
413
 
 
414
Provides access to all of the Class::Meta::Method objects that describe the
 
415
class' methods, and provide indirect execution of those constructors.
 
416
 
 
417
=back
 
418
 
 
419
=head3 L<Class::Meta::Constructor|Class::Meta::Constructor>
 
420
 
 
421
Describes a class constructor. Typically a class will have only a single
 
422
constructor, but there could be more, and client code doesn't necessarily know
 
423
its name. Class::Meta::Constructor objects resolve these issues by describing
 
424
all of the constructors in a class. The most useful methods are:
 
425
 
 
426
=over 4
 
427
 
 
428
=item name
 
429
 
 
430
Returns the name of the constructor, such as "new".
 
431
 
 
432
=item call
 
433
 
 
434
Calls the constructor on an object, passing in the arguments passed to
 
435
C<call()> itself.
 
436
 
 
437
=back
 
438
 
 
439
=head3 L<Class::Meta::Attribute|Class::Meta::Attribute>
 
440
 
 
441
Describes a class attribute, including its name and data type. Attribute
 
442
objects are perhaps the most useful Class::Meta objects, in that they can
 
443
provide a great deal of information about the structure of a class. The most
 
444
interesting methods are:
 
445
 
 
446
=over 4
 
447
 
 
448
=item name
 
449
 
 
450
Returns the name of the attribute.
 
451
 
 
452
=item type
 
453
 
 
454
Returns the name of the attribute's data type.
 
455
 
 
456
=item required
 
457
 
 
458
Returns true if the attribute is required to have a value.
 
459
 
 
460
=item once
 
461
 
 
462
Returns true if the attribute value can be set to a defined value only once.
 
463
 
 
464
=item set
 
465
 
 
466
Sets the value of an attribute on an object.
 
467
 
 
468
=item get
 
469
 
 
470
Returns the value of an attribute on an object.
 
471
 
 
472
=back
 
473
 
 
474
=head3 L<Class::Meta::Method|Class::Meta::Method>
 
475
 
 
476
Describes a method of a class, including its name and context (class
 
477
vs. instance). The relevant methods are:
 
478
 
 
479
=over 4
 
480
 
 
481
=item name
 
482
 
 
483
The method name.
 
484
 
 
485
=item context
 
486
 
 
487
The context of the method indicated by a value corresponding to either
 
488
Class::Meta::OBJECT or Class::Meta::CLASS.
 
489
 
 
490
=item call
 
491
 
 
492
Calls the method, passing in the arguments passed to C<call()> itself.
 
493
 
 
494
=back
 
495
 
 
496
Consult the documentation of the individual classes for a complete description
 
497
of their interfaces.
 
498
 
 
499
=cut
 
500
 
 
501
##############################################################################
 
502
# Class Methods
 
503
##############################################################################
 
504
 
 
505
=head1 INTERFACE
 
506
 
 
507
=head2 Class Methods
 
508
 
 
509
=head3 default_error_handler
 
510
 
 
511
  Class::Meta->default_error_handler($code);
 
512
  my $default_error_handler = Class::Meta->default_error_handler;
 
513
 
 
514
Sets the default error handler for Class::Meta classes. If no C<error_handler>
 
515
attribute is passed to new, then this error handler will be associated with
 
516
the new class. The default default error handler uses C<Carp::croak()> to
 
517
handle errors.
 
518
 
 
519
Note that if other modules are using Class::Meta that they will use your
 
520
default error handler unless you reset the default error handler to its
 
521
original value before loading them.
 
522
 
 
523
=head3 handle_error
 
524
 
 
525
  Class::Meta->handle_error($err);
 
526
 
 
527
Uses the code reference returned by C<default_error_handler()> to handle an
 
528
error. Used internally Class::Meta classes when no Class::Meta::Class object
 
529
is available. Probably not useful outside of Class::Meta unless you're
 
530
creating your own accessor generation class. Use the C<handle_error()>
 
531
instance method in Class::Meta::Class, instead.
 
532
 
 
533
=head3 for_key
 
534
 
 
535
  my $class = Class::Meta->for_key($key);
 
536
 
 
537
Returns the Class::Meta::Class object for a class by its key name. This can be
 
538
useful in circumstances where the key has been used to track a class, and you
 
539
need to get a handle on that class. With the class package name, you can of
 
540
course simply call C<< $pkg->my_class >>; this method is the solution for
 
541
getting the class object for a class key.
 
542
 
 
543
=head3 keys
 
544
 
 
545
  my @keys = Class::Meta->keys;
 
546
 
 
547
Returns the keys for all Class::Meta::Class objects.  The order of keys is
 
548
not guaranteed.  In scalar context, this method returns an array reference
 
549
containing the keys.
 
550
 
 
551
=head3 clear
 
552
 
 
553
  Class::Meta->clear;
 
554
  Class::Meta->clear($key);
 
555
 
 
556
Called without arguments, C<clear> will remove all
 
557
L<Class::Meta::Class|Class::Meta::Class> objects from memory. Called with an
 
558
argument, C<clear> attempts to remove only that key from memory. Calling it
 
559
with a non-existent key is a no-op.
 
560
 
 
561
In general, you probably won't want to use this method, except perhaps in
 
562
tests, when you might need to do funky things with your classes.
 
563
 
 
564
=cut
 
565
 
 
566
##############################################################################
 
567
# Constructors                                                               #
 
568
##############################################################################
 
569
 
 
570
=head2 Constructors
 
571
 
 
572
=head3 new
 
573
 
 
574
  my $cm = Class::Meta->new( key => $key );
 
575
 
 
576
Constructs and returns a new Class::Meta object that can then be used to
 
577
define and build the complete interface of a class. The supported parameters
 
578
are:
 
579
 
 
580
=over 4
 
581
 
 
582
=item package
 
583
 
 
584
The package that defines the class. Defaults to the package of the code
 
585
that calls C<new()>.
 
586
 
 
587
=item key
 
588
 
 
589
A key name that uniquely identifies a class within an application. Defaults to
 
590
the value of the C<package> parameter if not specified.
 
591
 
 
592
=item abstract
 
593
 
 
594
A boolean indicating whether the class being defined is an abstract class. An
 
595
abstract class, also known as a "virtual" class, is not intended to be used
 
596
directly. No objects of an abstract class should every be created. Instead,
 
597
classes that inherit from an abstract class must be implemented.
 
598
 
 
599
=item trust
 
600
 
 
601
An array reference of key names or packages that are trusted by the class.
 
602
 
 
603
  trust => ['Foo::Bar', 'Foo::Bat'],
 
604
 
 
605
Trusted packages and the classes that inherit from them can retrieve trusted
 
606
attributes and methods of the class. Trusted packages need not be Class::Meta
 
607
classes. Trusted classes do not include the declaring class by default, so if
 
608
you want the class that declares an attribute to be able to use trusted
 
609
attribute accessors, be sure to include it in the list of trusted packages:
 
610
 
 
611
  trust => [__PACKAGE__, 'Foo::Bar', 'Foo::Bat'],
 
612
 
 
613
If you need to trust a single class, you may pass in the key name or package
 
614
of that class rather than an array reference:
 
615
 
 
616
  trust => 'Foo::Bar',
 
617
 
 
618
=item class_class
 
619
 
 
620
The name of a class that inherits from Class::Meta::Class to be used to create
 
621
all of the class objects for the class. Defaults to Class::Meta::Class.
 
622
 
 
623
=item constructor_class
 
624
 
 
625
The name of a class that inherits from Class::Meta::Constructor to be used to
 
626
create all of the constructor objects for the class. Defaults to
 
627
Class::Meta::Constructor.
 
628
 
 
629
=item attribute_class
 
630
 
 
631
The name of a class that inherits from Class::Meta::Attribute to be used to
 
632
create all of the attribute objects for the class. Defaults to
 
633
Class::Meta::Attribute.
 
634
 
 
635
=item method_class
 
636
 
 
637
The name of a class that inherits from Class::Meta::Method to be used to
 
638
create all of the method objects for the class. Defaults to
 
639
Class::Meta::Method.
 
640
 
 
641
=item error_handler
 
642
 
 
643
A code reference that will be used to handle errors thrown by the methods
 
644
created for the new class. Defaults to the value returned by
 
645
C<< Class::Meta->default_error_handler >>.
 
646
 
 
647
=back
 
648
 
 
649
=cut
 
650
 
 
651
##############################################################################
 
652
# Dependencies                                                               #
 
653
##############################################################################
 
654
use 5.006001;
 
655
use strict;
 
656
 
 
657
##############################################################################
 
658
# Constants                                                                  #
 
659
##############################################################################
 
660
 
 
661
# View. These determine who can get metadata objects back from method calls.
 
662
use constant PRIVATE   => 0x01;
 
663
use constant PROTECTED => 0x02;
 
664
use constant TRUSTED   => 0x03;
 
665
use constant PUBLIC    => 0x04;
 
666
 
 
667
# Authorization. These determine what kind of accessors (get, set, both, or
 
668
# none) are available for a given attribute or method.
 
669
use constant NONE      => 0x01;
 
670
use constant READ      => 0x02;
 
671
use constant WRITE     => 0x03;
 
672
use constant RDWR      => 0x04;
 
673
 
 
674
# Method generation. These tell Class::Meta which accessors to create. Use
 
675
# NONE above for NONE. These will use the values in the authz argument by
 
676
# default. They're separate because sometimes an accessor needs to be built
 
677
# by hand, rather than custom-generated by Class::Meta, and the
 
678
# authorization needs to reflect that.
 
679
use constant GET       => READ;
 
680
use constant SET       => WRITE;
 
681
use constant GETSET    => RDWR;
 
682
 
 
683
# Method and attribute context.
 
684
use constant CLASS     => 0x01;
 
685
use constant OBJECT    => 0x02;
 
686
 
 
687
##############################################################################
 
688
# Dependencies that rely on the above constants                              #
 
689
##############################################################################
 
690
use Class::Meta::Type;
 
691
use Class::Meta::Class;
 
692
use Class::Meta::Constructor;
 
693
use Class::Meta::Attribute;
 
694
use Class::Meta::Method;
 
695
 
 
696
##############################################################################
 
697
# Package Globals                                                            #
 
698
##############################################################################
 
699
our $VERSION = "0.52";
 
700
 
 
701
##############################################################################
 
702
# Private Package Globals
 
703
##############################################################################
 
704
{
 
705
    my (%classes, %keys);
 
706
    my $error_handler = sub {
 
707
        require Carp;
 
708
        our @CARP_NOT = qw(Class::Meta
 
709
                           Class::Meta::Attribute
 
710
                           Class::Meta::Constructor
 
711
                           Class::Meta::Method
 
712
                           Class::Meta::Type
 
713
                           Class::Meta::Types::Numeric
 
714
                           Class::Meta::Types::String
 
715
                           Class::Meta::AccessorBuilder);
 
716
        # XXX Make sure Carp doesn't point to Class/Meta/Constructor.pm when
 
717
        # an exception is thrown by Class::Meta::AccessorBuilder. I have no
 
718
        # idea why this is necessary for AccessorBuilder but nowhere else!
 
719
        # Damn Carp.
 
720
        @Class::Meta::AccessorBuilder::CARP_NOT = @CARP_NOT
 
721
          if caller(1) eq 'Class::Meta::AccessorBuilder';
 
722
        Carp::croak(@_);
 
723
    };
 
724
 
 
725
    sub default_error_handler {
 
726
        shift;
 
727
        return $error_handler unless @_;
 
728
        $error_handler->("Error handler must be a code reference")
 
729
          unless ref $_[0] eq 'CODE';
 
730
        return $error_handler = shift;
 
731
    }
 
732
 
 
733
    sub handle_error {
 
734
        shift;
 
735
        $error_handler->(@_);
 
736
    }
 
737
 
 
738
    sub for_key { $keys{$_[1]} }
 
739
 
 
740
    sub keys    { wantarray ? keys %keys : [keys %keys] }
 
741
 
 
742
    sub clear   { shift; @_ ? delete $keys{+shift} : undef %keys }
 
743
 
 
744
    sub new {
 
745
        my $pkg = shift;
 
746
 
 
747
        # Make sure we can get all the arguments.
 
748
        $error_handler->("Odd number of parameters in call to new() when named "
 
749
                         . "parameters were expected" ) if @_ % 2;
 
750
        my %p = @_;
 
751
 
 
752
        # Class defaults to caller. Key defaults to class.
 
753
        $p{package} ||= caller;
 
754
        $p{key} ||= $p{package};
 
755
 
 
756
        # Configure the error handler.
 
757
        if (exists $p{error_handler}) {
 
758
            $error_handler->("Error handler must be a code reference")
 
759
              unless ref $p{error_handler} eq 'CODE';
 
760
        } else {
 
761
            $p{error_handler} = $pkg->default_error_handler;
 
762
        }
 
763
 
 
764
        # Check to make sure we haven't created this class already.
 
765
        $p{error_handler}->("Class object for class '$p{package}' "
 
766
                            . "already exists")
 
767
          if $classes{$p{package}};
 
768
 
 
769
        $p{class_class}       ||= 'Class::Meta::Class';
 
770
        $p{constructor_class} ||= 'Class::Meta::Constructor';
 
771
        $p{attribute_class}   ||= 'Class::Meta::Attribute';
 
772
        $p{method_class}      ||= 'Class::Meta::Method';
 
773
 
 
774
        # Instantiate and cache Class object.
 
775
        $keys{$p{key}} = $classes{$p{package}} = $p{class_class}->new(\%p);
 
776
 
 
777
        # Copy its parents' attributes and return.
 
778
        $classes{$p{package}}->_inherit( \%classes, 'attr');
 
779
 
 
780
        # Return!
 
781
        return bless { package => $p{package} }, ref $pkg || $pkg;
 
782
    }
 
783
 
 
784
 
 
785
##############################################################################
 
786
# add_constructor()
 
787
 
 
788
=head3 add_constructor
 
789
 
 
790
  $cm->add_constructor( name   => 'new',
 
791
                        create => 1 );
 
792
 
 
793
Creates and returns a Class::Meta::Constructor object that describes a
 
794
constructor for the class. The supported parameters are:
 
795
 
 
796
=over 4
 
797
 
 
798
=item name
 
799
 
 
800
The name of the constructor. The name must consist of only alphanumeric
 
801
characters or "_".
 
802
 
 
803
=item label
 
804
 
 
805
A label for the constructor. Generally used for displaying its name in a user
 
806
interface. Optional.
 
807
 
 
808
=item desc
 
809
 
 
810
A description of the constructor. Possibly useful for displaying help text in
 
811
a user interface. Optional.
 
812
 
 
813
=item view
 
814
 
 
815
The visibility of the constructor. The possible values are defined by the
 
816
following constants:
 
817
 
 
818
=over 4
 
819
 
 
820
=item Class::Meta::PUBLIC
 
821
 
 
822
Can be used by any client.
 
823
 
 
824
=item Class::Meta::PRIVATE
 
825
 
 
826
Can only be used by the declaring class.
 
827
 
 
828
=item Class::Meta::TRUSTED
 
829
 
 
830
Can only be used by the classes specified by the C<trust> parameter to
 
831
C<new()>.
 
832
 
 
833
=item Class::Meta::PROTECTED
 
834
 
 
835
Can only be used by the declaring class or by classes that inherit from it.
 
836
 
 
837
=back
 
838
 
 
839
Defaults to Class::Meta::PUBLIC if not defined.
 
840
 
 
841
=item caller
 
842
 
 
843
A code reference that calls the constructor. Defaults to a code reference that
 
844
calls a method with the name provided by the C<name> attribute on the class
 
845
being defined.
 
846
 
 
847
=back
 
848
 
 
849
=cut
 
850
 
 
851
    sub add_constructor {
 
852
        my $class = $classes{ shift->{package} };
 
853
        push @{$class->{build_ctor_ord}},
 
854
          $class->{constructor_class}->new($class, @_);
 
855
        return $class->{build_ctor_ord}[-1];
 
856
    }
 
857
 
 
858
##############################################################################
 
859
# add_attribute()
 
860
 
 
861
=head3 add_attribute
 
862
 
 
863
  $cm->add_attribute( name => 'tail',
 
864
                      type => 'scalar' );
 
865
 
 
866
Creates and returns a Class::Meta::Attribute object that describes an
 
867
attribute of the class. The supported parameters are:
 
868
 
 
869
=over 4
 
870
 
 
871
=item type
 
872
 
 
873
The data type of the attribute. See L</"Data Types"> for some possible values
 
874
for this parameter. Required.
 
875
 
 
876
=item name
 
877
 
 
878
The name of the attribute. The name must consist of only alphanumeric
 
879
characters or "_". Required.
 
880
 
 
881
=item required
 
882
 
 
883
A boolean value indicating whether the attribute is required to have a value.
 
884
Defaults to false.
 
885
 
 
886
=item once
 
887
 
 
888
A boolean value indicating whether the attribute can be set to a defined value
 
889
only once. Defaults to false.
 
890
 
 
891
=item label
 
892
 
 
893
A label for the attribute. Generally used for displaying its name in a user
 
894
interface. Optional.
 
895
 
 
896
=item desc
 
897
 
 
898
A description of the attribute. Possibly useful for displaying help text in a
 
899
user interface. Optional.
 
900
 
 
901
=item view
 
902
 
 
903
The visibility of the attribute. See the description of the C<view> parameter
 
904
to C<add_constructor> for a description of its value.
 
905
 
 
906
=item authz
 
907
 
 
908
The authorization of the attribute. This value indicates whether it is
 
909
read-only, write-only, read/write, or inaccessible. The possible values are
 
910
defined by the following constants:
 
911
 
 
912
=over 4
 
913
 
 
914
=item Class::Meta::READ
 
915
 
 
916
=item Class::Meta::WRITE
 
917
 
 
918
=item Class::Meta::RDWR
 
919
 
 
920
=item Class::Meta::NONE
 
921
 
 
922
=back
 
923
 
 
924
Defaults to Class::Meta::RDWR if not defined.
 
925
 
 
926
=item create
 
927
 
 
928
Indicates what type of accessor or accessors are to be created for the
 
929
attribute.
 
930
 
 
931
=over 4
 
932
 
 
933
=item Class::Meta::GET
 
934
 
 
935
Create read-only accessor(s).
 
936
 
 
937
=item Class::Meta::SET
 
938
 
 
939
Create write-only accessor(s).
 
940
 
 
941
=item Class::Meta::GETSET
 
942
 
 
943
Create read/write accessor(s).
 
944
 
 
945
=item Class::Meta::NONE
 
946
 
 
947
Create no accessors.
 
948
 
 
949
=back
 
950
 
 
951
If not unspecified, the value of the C<create> parameter will correspond to
 
952
the value of the C<authz> parameter like so:
 
953
 
 
954
  authz       create
 
955
  ------------------
 
956
  READ   =>   GET
 
957
  WRITE  =>   SET
 
958
  RDWR   =>   GETSET
 
959
  NONE   =>   NONE
 
960
 
 
961
The C<create> parameter differs from the C<authz> parameter in case you've
 
962
taken it upon yourself to create some accessors, and therefore don't need
 
963
Class::Meta to do so. For example, if you were using standard Perl-style
 
964
accessors, and needed to do something a little different by coding your own
 
965
accessor, you'd specify it like this:
 
966
 
 
967
  $cm->add_attribute( name   => $name,
 
968
                      type   => $type,
 
969
                      authz  => Class::Meta::RDWR,
 
970
                      create => Class::Meta::NONE );
 
971
 
 
972
Just be sure that your custom accessor compiles before you call
 
973
C<< $cm->build >> so that Class::Meta::Attribute can get a handle on it for
 
974
its C<get()> and/or C<set()> methods.
 
975
 
 
976
=item context
 
977
 
 
978
The context of the attribute. This indicates whether it's a class attribute or
 
979
an object attribute. The possible values are defined by the following
 
980
constants:
 
981
 
 
982
=over 4
 
983
 
 
984
=item Class::Meta::CLASS
 
985
 
 
986
=item Class::Meta::OBJECT
 
987
 
 
988
=back
 
989
 
 
990
=item default
 
991
 
 
992
The default value for the attribute, if any. This may be either a literal
 
993
value or a code reference that will be executed to generate a default value.
 
994
 
 
995
=item override
 
996
 
 
997
If an attribute being added to a class has the same name as an attribute in a
 
998
parent class, Class::Meta will normally throw an exception. However, in some
 
999
cases you might want to override an attribute in a parent class to change its
 
1000
properties. In such a case, pass a true value to the C<override> parameter to
 
1001
override the attribute and avoid the exception.
 
1002
 
 
1003
=back
 
1004
 
 
1005
=cut
 
1006
 
 
1007
    sub add_attribute {
 
1008
        my $class = $classes{ shift->{package} };
 
1009
        push @{$class->{build_attr_ord}},
 
1010
          $class->{attribute_class}->new($class, @_);
 
1011
        return $class->{build_attr_ord}[-1];
 
1012
    }
 
1013
 
 
1014
##############################################################################
 
1015
# add_method()
 
1016
 
 
1017
=head3 add_method
 
1018
 
 
1019
  $cm->add_method( name => 'wag' );
 
1020
 
 
1021
Creates and returns a Class::Meta::Method object that describes a method of
 
1022
the class. The supported parameters are:
 
1023
 
 
1024
=over 4
 
1025
 
 
1026
=item name
 
1027
 
 
1028
The name of the method. The name must consist of only alphanumeric
 
1029
characters or "_".
 
1030
 
 
1031
=item label
 
1032
 
 
1033
A label for the method. Generally used for displaying its name in a user
 
1034
interface. Optional.
 
1035
 
 
1036
=item desc
 
1037
 
 
1038
A description of the method. Possibly useful for displaying help text in a
 
1039
user interface. Optional.
 
1040
 
 
1041
=item view
 
1042
 
 
1043
The visibility of the method. See the description of the C<view> parameter to
 
1044
C<add_constructor> for a description of its value.
 
1045
 
 
1046
=item code
 
1047
 
 
1048
You can implicitly define the method in your class by passing a code reference
 
1049
via teh C<code> parameter. Once C<build()> is called,
 
1050
L<Kinetic::Meta::Method|Kinetic::Meta::Method> will install the method into
 
1051
the package for which the Class::Meta object was defined, and with the name
 
1052
specified via the C<name> parameter. This can make it easy to declare an
 
1053
entire class in a single Class::Meta declaration.
 
1054
 
 
1055
=item context
 
1056
 
 
1057
The context of the method. This indicates whether it's a class method or an
 
1058
object method. See the description of the C<context> parameter to C<add_attribute>
 
1059
for a description of its value.
 
1060
 
 
1061
=item caller
 
1062
 
 
1063
A code reference that calls the method. This code reference will be be used by
 
1064
the C<call()> method of L<Class::Meta::Method|Class::Meta::Method> to execute
 
1065
the method on behalf of an object. Defaults to a code reference that calls a
 
1066
method with the name provided by the C<name> attribute on the class being
 
1067
defined.
 
1068
 
 
1069
=item args
 
1070
 
 
1071
A description of the arguments to the method. This can be anything you like,
 
1072
but I recommend something like a string for a single argument, an array
 
1073
reference for a list of arguments, or a hash reference for parameter
 
1074
arguments.
 
1075
 
 
1076
=item returns
 
1077
 
 
1078
A string describing the return value or values of the method.
 
1079
 
 
1080
=back
 
1081
 
 
1082
=cut
 
1083
 
 
1084
    sub add_method {
 
1085
        my $class = $classes{ shift->{package} };
 
1086
        push @{$class->{build_meth_ord}},
 
1087
          $class->{method_class}->new($class, @_);
 
1088
        return $class->{build_meth_ord}[-1];
 
1089
    }
 
1090
 
 
1091
##############################################################################
 
1092
# Instance Methods                                                           #
 
1093
##############################################################################
 
1094
 
 
1095
=head2 Instance Methods
 
1096
 
 
1097
=head3 class
 
1098
 
 
1099
  my $class = $cm->class;
 
1100
 
 
1101
Returns the instance of the Class::Meta::Class object that will be used to
 
1102
provide the introspection API for the class being generated.
 
1103
 
 
1104
=cut
 
1105
 
 
1106
    # Simple accessor.
 
1107
    sub class { $classes{ $_[0]->{package} } }
 
1108
 
 
1109
##############################################################################
 
1110
# build()
 
1111
 
 
1112
=head3 build
 
1113
 
 
1114
  $cm->build;
 
1115
 
 
1116
Builds the class defined by the Class::Meta object, including the
 
1117
C<my_class()> class method, and all requisite constructors and accessors.
 
1118
 
 
1119
=cut
 
1120
 
 
1121
    sub build {
 
1122
        my $self = shift;
 
1123
        my $class = $classes{ $self->{package} };
 
1124
 
 
1125
        # Build the attribute accessors.
 
1126
        if (my $attrs = delete $class->{build_attr_ord}) {
 
1127
            $_->build($class) for @$attrs;
 
1128
        }
 
1129
 
 
1130
        # Build the constructors.
 
1131
        if (my $ctors = delete $class->{build_ctor_ord}) {
 
1132
            $_->build(\%classes) for @$ctors;
 
1133
        }
 
1134
 
 
1135
        # Build the methods.
 
1136
        if (my $meths = delete $class->{build_meth_ord}) {
 
1137
            $_->build(\%classes) for @$meths;
 
1138
        }
 
1139
 
 
1140
        # Build the class; it needs to get at the data added by the above
 
1141
        # calls to build() methods.
 
1142
        $class->build(\%classes);
 
1143
 
 
1144
        # Build the Class::Meta::Class accessor and key shortcut.
 
1145
        no strict 'refs';
 
1146
        *{"$class->{package}::my_class"} = sub { $class };
 
1147
 
 
1148
        return $self;
 
1149
    }
 
1150
}
 
1151
 
 
1152
1;
 
1153
__END__
 
1154
 
 
1155
=head1 TO DO
 
1156
 
 
1157
=over 4
 
1158
 
 
1159
=item *
 
1160
 
 
1161
Make class attribute accessors behave as they do in Class::Data::Inheritable.
 
1162
 
 
1163
=item *
 
1164
 
 
1165
Modify class attribute accessors so that they are thread safe. This will
 
1166
involve sharing the attributes across threads, and locking them before
 
1167
changing their values. If they've also been made to behave as they do in
 
1168
Class::Data::Inheritable, we'll have to figure out a way to make it so that
 
1169
newly generated accessors for subclasses are shared between threads, too. This
 
1170
may not be easy.
 
1171
 
 
1172
=back
 
1173
 
 
1174
=head1 BUGS
 
1175
 
 
1176
Please send bug reports to <bug-class-meta@rt.cpan.org> or report them via the
 
1177
CPAN Request Tracker at L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Class-Meta>.
 
1178
 
 
1179
=head1 AUTHOR
 
1180
 
 
1181
David Wheeler <david@kineticode.com>
 
1182
 
 
1183
=head1 SEE ALSO
 
1184
 
 
1185
Other classes of interest within the Class::Meta distribution include:
 
1186
 
 
1187
=over 4
 
1188
 
 
1189
=item L<Class::Meta::Class|Class::Meta::Class>
 
1190
 
 
1191
=item L<Class::Meta::Constructor|Class::Meta::Constructor>
 
1192
 
 
1193
=item L<Class::Meta::Attribute|Class::Meta::Attribute>
 
1194
 
 
1195
=item L<Class::Meta::Method|Class::Meta::Method>
 
1196
 
 
1197
=item L<Class::Meta::Type|Class::Meta::Type>
 
1198
 
 
1199
=item L<Class::Meta::Types::Perl|Class::Meta::Types::Perl>
 
1200
 
 
1201
=item L<Class::Meta::Types::String|Class::Meta::Types::String>
 
1202
 
 
1203
=item L<Class::Meta::Types::Boolean|Class::Meta::Types::Boolean>
 
1204
 
 
1205
=item L<Class::Meta::Types::Numeric|Class::Meta::Types::Numeric>
 
1206
 
 
1207
=back
 
1208
 
 
1209
For comparative purposes, you might also want to check out these fine modules:
 
1210
 
 
1211
=over
 
1212
 
 
1213
=item L<Class::Accessor|Class::Accessor>
 
1214
 
 
1215
Accessor and constructor automation.
 
1216
 
 
1217
=item L<Params::Validate|Params::Validate>
 
1218
 
 
1219
Parameter validation.
 
1220
 
 
1221
=item L<Class::Contract|Class::Contract>
 
1222
 
 
1223
Design by contract.
 
1224
 
 
1225
=item L<Class::Tangram|Class::Tangram>
 
1226
 
 
1227
Accessor automation and data validation for Tangram applications.
 
1228
 
 
1229
=item L<Class::Maker|Class::Maker>
 
1230
 
 
1231
An ambitious yet underdocumented module that also manages accessor and
 
1232
constructor generation, data validation, and provides a reflection API. It
 
1233
also supports serialization.
 
1234
 
 
1235
=back
 
1236
 
 
1237
=head1 COPYRIGHT AND LICENSE
 
1238
 
 
1239
Copyright (c) 2002-2005, David Wheeler. All Rights Reserved.
 
1240
 
 
1241
This module is free software; you can redistribute it and/or modify it under
 
1242
the same terms as Perl itself.
 
1243
 
 
1244
=cut