new_instances
[gitmo/Class-MOP.git] / examples / LazyClass.pod
index e3c0b42..1847939 100644 (file)
@@ -1,40 +1,29 @@
 
 package # hide the package from PAUSE
-    LazyClass;
+    LazyClass::Attribute;
 
 use strict;
 use warnings;
 
-our $VERSION = '0.02';
-
-use base 'Class::MOP::Class';
-
-sub construct_instance {
-    my ($class, %params) = @_;
-    my $instance = {};
-    foreach my $attr ($class->compute_all_applicable_attributes()) {
-        # if the attr has an init_arg, use that, otherwise,
-        # use the attributes name itself as the init_arg
-        my $init_arg = $attr->init_arg();
-        # try to fetch the init arg from the %params ...
-        my $val;        
-        $val = $params{$init_arg} if exists $params{$init_arg};
-        # now add this to the instance structure
-        # only if we have found a value at all
-        $instance->{$attr->name} = $val if defined $val;
-    }
-    return $instance;    
-}
+use Carp 'confess';
 
-package # hide the package from PAUSE
-    LazyClass::Attribute;
+our $VERSION = '0.03';
 
-use strict;
-use warnings;
+use base 'Class::MOP::Attribute';
 
-our $VERSION = '0.02';
+sub initialize_instance_slot {
+    my ($self, $class, $meta_instance, $params) = @_;
+    # if the attr has an init_arg, use that, otherwise,
+    # use the attributes name itself as the init_arg
+    my $init_arg = $self->init_arg();
+    # try to fetch the init arg from the %params ...
+    my $val;        
+    $val = $params->{$init_arg} if exists $params->{$init_arg};
+    # now add this to the instance structure
+    # only if we have found a value at all
+    $meta_instance->add_slot($self->name, $val) if defined $val;    
+}
 
-use base 'Class::MOP::Attribute';
 
 sub generate_accessor_method {
     my ($self, $attr_name) = @_;
@@ -55,6 +44,7 @@ sub generate_accessor_method {
 sub generate_reader_method {
     my ($self, $attr_name) = @_; 
     sub {
+        confess "Cannot assign a value to a read-only accessor" if @_ > 1;        
         if (!exists $_[0]->{$attr_name}) {
             my $attr = $self->associated_class->get_attribute($attr_name);
             $_[0]->{$attr_name} = $attr->has_default ? $attr->default($_[0]) : undef;           
@@ -77,7 +67,7 @@ LazyClass - An example metaclass with lazy initialization
 
   package BinaryTree;
   
-  use metaclass 'LazyClass' => (
+  use metaclass 'Class::MOP::Class' => (
       ':attribute_metaclass' => 'LazyClass::Attribute'
   );
   
@@ -96,9 +86,9 @@ LazyClass - An example metaclass with lazy initialization
       default => sub { BinaryTree->new() }    
   ));    
   
-  sub new {
+  sub new  {
       my $class = shift;
-      bless $class->meta->construct_instance(@_) => $class;
+      $class->meta->new_object(@_);
   }
   
   # ... later in code