The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Type::Tiny::Manual::UsingWithOther - how to use Type::Tiny and Type::Library with other OO frameworks

DESCRIPTION

Class::InsideOut

You want Class::InsideOut 1.13 or above, which has support for blessed and overloaded objects (including Type::Tiny type constraints) for the get_hook and set_hook options.

   {
      package Person;
      
      use Class::InsideOut qw( public );
      use Types::Standard qw( Str Int );
      use Type::Utils qw( declare as where inline_as coerce from );
      
      public name => my %_name, {
         set_hook => Str,
      };
      
      my $PositiveInt = declare
         as        Int,
         where     {  $_ > 0  },
         inline_as { "$_ =~ /^[0-9]\$/ and $_ > 0" };
      
      coerce $PositiveInt, from Int, q{ abs $_ };
      
      public age => my %_age, {
         set_hook => sub { $_ = $PositiveInt->assert_coerce($_) },
      };
      
      sub get_older {
         my $self = shift;
         my ($years) = @_;
         $PositiveInt->assert_valid($years);
         $self->_set_age($self->age + $years);
      }
   }

I probably need to make coercions a little prettier.

See also: t/25_accessor_hooks_typetiny.t and t/Object/HookedTT.pm in the Class::InsideOut test suite.

Params::Check and Object::Accessor

The Params::Check allow() function, the allow option for the Params::Check check() function, and the input validation mechanism for Object::Accessor all work in the same way, which is basically a limited pure-Perl implementation of the smart match operator. While this doesn't directly support Type::Tiny constraints, it does support coderefs. You can use Type::Tiny's compiled_check method to obtain a suitable coderef.

Param::Check example:

   my $tmpl = {
      name => { allow => Str->compiled_check },
      age  => { allow => Int->compiled_check },
   };
   check($tmpl, { name => "Bob", age => 32 })
      or die Params::Check::last_error();

Object::Accessor example:

   my $obj = Object::Accessor->new;
   $obj->mk_accessors(
      { name => Str->compiled_check },
      { age  => Int->compiled_check },
   );

Caveat: Object::Accessor doesn't die when a value fails to meet its type constraint; instead it outputs a warning to STDERR. This behaviour can be changed by setting $Object::Accessor::FATAL = 1.

AUTHOR

Toby Inkster <tobyink@cpan.org>.

COPYRIGHT AND LICENCE

This software is copyright (c) 2013 by Toby Inkster.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

DISCLAIMER OF WARRANTIES

THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.