Type::Tiny::Manual::UsingWithOther - how to use Type::Tiny and Type::Library with other OO frameworks
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.
get_hook
set_hook
{ 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.
t/25_accessor_hooks_typetiny.t
t/Object/HookedTT.pm
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.
allow()
allow
check()
compiled_check
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.
$Object::Accessor::FATAL = 1
Toby Inkster <tobyink@cpan.org>.
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.
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.
To install Type::Tiny, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Type::Tiny
CPAN shell
perl -MCPAN -e shell install Type::Tiny
For more information on module installation, please visit the detailed CPAN module installation guide.