File Coverage

blib/lib/Class/Meta.pm
Criterion Covered Total %
statement 131 131 100.0
branch 28 30 93.3
condition 14 20 70.0
subroutine 36 36 100.0
pod 11 11 100.0
total 220 228 96.4


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