Better way of declaring classes?

Ovid on 2006-08-08T07:11:39

If you've seen Class::Meta, it's quite possible that you were looking for something which could do what it does, but saw the interface and turned away and shuddered. Now, borrowing heavily from Moose, David's released Class::Meta::Express. So if you use Class::Meta, you might want to consider a switch from this:

  use Class::Meta;

  BEGIN {

      # Create a Class::Meta object for this class.
      my $cm = Class::Meta->new( key => 'thingy' );

      # Add a constructor.
      $cm->add_constructor( name   => 'new' );

      # Add a couple of attributes with generated accessors.
      $cm->add_attribute(
          name     => 'id',
          is       => 'integer',
          required => 1,
      );

      $cm->add_attribute(
          name     => 'name',
          is       => 'string',
          required => 1,
      );

      $cm->add_attribute(
          name    => 'age',
          is      => 'integer',
      );

     # Add a custom method.
      $cm->add_method(
          name => 'chk_pass',
          code => sub { return 'code' },
      );
      $cm->build;
  }

To this identical result, but nicer interface:

  use Class::Meta::Express;

  BEGIN {

      # Create a Class::Meta object for this class.
      meta thingy => ( default_type => 'integer' );

      # Add a constructor.
      ctor 'new';

      # Add a couple of attributes with generated accessors.
      has id   => ( required => 1 );
      has name => ( is => 'string', required => 1 );
      has 'age';

     # Add a custom method.
      method chk_pass => sub { return 'code' };

      build;
  }

Much cleaner! In fact, I would recommend this over my own Class::Meta::Declare because while my interface is nicer than Class::Meta's, the "express" interface is far better.

That being said, I'm going to have to have a look at Moose. It seems pretty interesting and easy to use.