Class::XSConstructor - a super-fast (but limited) constructor in XS
package Person { use Class::XSConstructor qw( name! age email phone ); use Class::XSAccessor { accessors => [qw( name age email phone )], exists_predicates => [qw( age email phone )], }; }
Class::XSAccessor is able to provide you with a constructor for your class, but it's fairly limited. It basically just does:
sub new { my $class = shift; bless { @_ }, ref($class)||$class; }
Class::XSConstructor goes a little further towards Moose-like constructors, adding the following features:
Supports initialization from a hashref as well as a list of key-value pairs.
Only initializes the attributes you specified. Given the example in the synposis:
my $obj = Person->new(name => "Alice", height => "170 cm");
The height will be ignored because it's not a defined attribute for the class.
Supports required attributes using an exclamation mark. The name attribute in the synopsis is required.
Provides support for type constraints.
use Types::Standard qw(Str Int); use Class::XSConstructor ( "name!" => Str, "age" => Int, "email" => Str, "phone" => Str, );
Type constraints can also be provided as coderefs returning a boolean:
use Types::Standard qw(Str Int); use Class::XSConstructor ( "name!" => Str, "age" => Int, "email" => sub { !ref($_[0]) and $_[0] =~ /\@/ }, "phone" => Str, );
Type constraints are likely to siginificantly slow down your constructor.
Note that Class::XSConstructor is only building your constructor for you. For read-write attributes, checking the type constraint in the accessor is your responsibility.
Supports Moose/Moo/Class::Tiny-style BUILD methods.
BUILD
Including __no_BUILD__.
__no_BUILD__
Inheritance will automatically work if you are inheriting from another Class::XSConstructor class, but you need to set @ISA before importing from Class::XSConstructor (which will happen at compile time!)
@ISA
An easy way to do this is to use parent before using Class::XSConstructor.
package Employee { use parent "Person"; use Class::XSConstructor qw( employee_id! ); use Class::XSAccessor { getters => [qw()] }; }
Please report any bugs to http://rt.cpan.org/Dist/Display.html?Queue=Class-XSConstructor.
Class::Tiny, Class::XSAccessor.
Toby Inkster <tobyink@cpan.org>.
To everybody in #xs on irc.perl.org.
This software is copyright (c) 2018 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 Class::XSConstructor, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Class::XSConstructor
CPAN shell
perl -MCPAN -e shell install Class::XSConstructor
For more information on module installation, please visit the detailed CPAN module installation guide.