Perl 模式¶
此文件使用 Perl 特定内容扩展 common/patterns.md。
仓库模式¶
DBI 或 DBIx::Class 用于接口背后:
package MyApp::Repo::User;
use Moo;
has dbh => (is => 'ro', required => 1);
sub find_by_id ($self, $id) {
my $sth = $self->dbh->prepare('SELECT * FROM users WHERE id = ?');
$sth->execute($id);
return $sth->fetchrow_hashref;
}
DTO / 值对象¶
使用 Moo 类和 Types::Standard(相当于 Python 的 dataclass):
package MyApp::DTO::User;
use Moo;
use Types::Standard qw(Str Int);
has name => (is => 'ro', isa => Str, required => 1);
has email => (is => 'ro', isa => Str, required => 1);
has age => (is => 'ro', isa => Int);
资源管理¶
- 始终使用带
autodie的 三参数 open - 文件操作使用 Path::Tiny
模块接口¶
使用 Exporter 'import' 和 @EXPORT_OK — 不使用 @EXPORT:
依赖管理¶
为可复现安装使用 cpanfile + carton:
参考¶
技能:在 perl-patterns 中查看全面的现代 Perl 模式和习语。
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC