require latest Moose
[gitmo/MooseX-StrictConstructor.git] / lib / MooseX / StrictConstructor.pm
1 package MooseX::StrictConstructor;
2
3 use strict;
4 use warnings;
5
6 our $VERSION = '0.08';
7 $VERSION = eval $VERSION;
8
9 use Moose 0.74 ();
10 use Moose::Exporter;
11 use Moose::Util::MetaRole;
12 use MooseX::StrictConstructor::Role::Object;
13 use MooseX::StrictConstructor::Role::Meta::Method::Constructor;
14
15
16 Moose::Exporter->setup_import_methods();
17
18 sub init_meta
19 {
20     shift;
21     my %p = @_;
22
23     Moose->init_meta(%p);
24
25     my $caller = $p{for_class};
26
27     Moose::Util::MetaRole::apply_metaclass_roles
28         ( for_class => $caller,
29           constructor_class_roles =>
30           ['MooseX::StrictConstructor::Role::Meta::Method::Constructor'],
31         );
32
33     Moose::Util::MetaRole::apply_base_class_roles
34         ( for_class => $caller,
35           roles =>
36           [ 'MooseX::StrictConstructor::Role::Object' ],
37         );
38
39     return $caller->meta();
40 }
41
42 1;
43
44 __END__
45
46 =pod
47
48 =head1 NAME
49
50 MooseX::StrictConstructor - Make your object constructors blow up on unknown attributes
51
52 =head1 SYNOPSIS
53
54     package My::Class;
55
56     use Moose;
57     use MooseX::StrictConstructor;
58
59     has 'size' => ...;
60
61     # then later ...
62
63     # this blows up because color is not a known attribute
64     My::Class->new( size => 5, color => 'blue' );
65
66 =head1 DESCRIPTION
67
68 Simply loading this module makes your constructors "strict". If your
69 constructor is called with an attribute init argument that your class
70 does not declare, then it calls "Carp::confess()". This is a great way
71 to catch small typos.
72
73 =head2 Subverting Strictness
74
75 You may find yourself wanting to have your constructor accept a
76 parameter which does not correspond to an attribute.
77
78 In that case, you'll probably also be writing a C<BUILD()> or
79 C<BUILDARGS()> method to deal with that parameter. In a C<BUILDARGS()>
80 method, you can simply make sure that this parameter is not included
81 in the hash reference you return. Otherwise, in a C<BUILD()> method,
82 you can delete it from the hash reference of parameters.
83
84   sub BUILD {
85       my $self   = shift;
86       my $params = shift;
87
88       if ( delete $params->{do_something} ) {
89           ...
90       }
91   }
92
93 =head1 AUTHOR
94
95 Dave Rolsky, C<< <autarch@urth.org> >>
96
97 =head1 BUGS
98
99 Please report any bugs or feature requests to
100 C<bug-moosex-strictconstructor@rt.cpan.org>, or through the web
101 interface at L<http://rt.cpan.org>.  I will be notified, and then
102 you'll automatically be notified of progress on your bug as I make
103 changes.
104
105 =head1 COPYRIGHT & LICENSE
106
107 Copyright 2007-2008 Dave Rolsky, All Rights Reserved.
108
109 This program is free software; you can redistribute it and/or modify
110 it under the same terms as Perl itself.
111
112 =cut