in reply to Re^5: If Perl 5 were to become Perl 7, what (backward-compatible) features would you want to see?
in thread If Perl 5 were to become Perl 7, what (backward-compatible) features would you want to see?
Ah, I've stumbled over this: Parameters which are only needed at object creation, but which don't need to stick around (or shouldn't, in the case of a password).
Contrary to my previous post, where I advocated to use this only to keep APIs compatible, this is another example where I find coercion to be an excellent tool. Something sort of like this (note I'm not familiar with Moo coercion which seems to be different from Moose coercion, so caution is advised):
Edited to add: 1nickt was faster and more comprehensive with the same proposal. I upvoted his, feel free to ignore mine.package Moo::Role::DBIConnection; use Moo::Role; use feature 'signatures'; no warnings 'experimental::signatures'; use DBI; our $VERSION = '0.01'; =head1 NAME Moo::Role::DBIConnection =head1 SYNOPSIS { package My::Example; use Moo 2; with 'Moo::Role::DBIConnection'; }; # Connect using the parameters my $writer = My::Example->new( dbh => { dsn => '...', user => '...', password => '...', options => '...', }, ); # ... or alternatively if you have a connection already my $writer2 = My::Example->new( dbh => $dbh, ); =cut has 'dbh' => ( is => 'ro', coerce => \&_coerce_db, ); sub _coerce_db { my $connection_data = shift; return UNIVERSAL::isa($connection_data,'DBI::db') ? $connection_data : DBI->connect( @$connection_data{qw(dsn user password options)} + ); } 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: If Perl 5 were to become Perl 7, what (backward-compatible) features would you want to see?
by 1nickt (Canon) on Oct 16, 2019 at 01:32 UTC | |
by Corion (Patriarch) on Oct 16, 2019 at 07:32 UTC |