这些是我的目标:
>关注Moose’Moose::Manual::BestPractices
,特别是:
>使用namespace :: autoclean和
>使用__PACKAGE __-> Meta-> make_immutable.
>为Result和ResultSet使用公共基类
>当使用任何魔术技巧时都有一个解释它们的评论(在研究过程中,我发现了一个指导子建构的指南{$_ [2]}由don’t ask解释)
>移动公共代码,例如MooseX :: NonMoose(如有必要)或__PACKAGE __-> load_components,按照DBIx::Class::Manual::Cookbook
的建议进入公共基类
这些是我遇到的问题:
>当使用__PACKAGE __-> Meta-> make_immutable时,我收到警告,比如没有为MyApp :: Schema :: Result :: MyTable内联’new’,因为它没有继承默认的Moose :: Object :: new
>将所有对__PACKAGE __-> load_components的调用移动到Result基类时,我的日期时间列没有被充气
解决方法
> make_immutable与非Moose新构造函数冲突:使用MooseX :: NonMoose自动处理;与其文件相比,不需要进一步的论据或选择;请注意,DBIx :: Class :: Schema没有新方法,因此MyApp :: Schema不需要这个帮助器
> InflateColumn :: DateTime在基类中加载时不膨胀:这是由赋予load_components()的组件顺序触发的;在文件中没有暗示订单应该重要,我已经提交了a bug report关于此;重新排序有帮助
使用上面的解决方案,我的示例DBIx :: Class模式与Moose看起来像这样:
架构类:
package MyApp::Schema; use Moose; # we want Moose use MooseX::MarkAsMethods autoclean => 1; # this helps removing unused symbols like Moose keywords # do NOT 'use MooseX::NonMoose' here because Schema class has no 'new' method extends 'DBIx::Class::Schema'; # the Moose way of inheritance # load all table modules automatically __PACKAGE__->load_namespaces( # ResultSet class for tables without custom ResultSet class # (would be DBIx::Class::ResultSet otherwise) default_resultset_class => '+MyApp::Schema::ResultSet',); # tell Moose this class is finished: some Moose stuff is removed and things go faster __PACKAGE__->Meta->make_immutable; 1;
通用结果基类:
# a base class for all table class of this app package MyApp::Schema::Result; use Moose; use MooseX::MarkAsMethods autoclean => 1; use MooseX::NonMoose; # this is important for correctly handling DBIx::Class' new extends 'DBIx::Class::Core'; # this is the right place to implement generic stuff # DBIx::Class::Cookbook recommends loading components in a central place __PACKAGE__->load_components(qw/ InflateColumn::DateTime ... /); __PACKAGE__->Meta->make_immutable; 1;
通用ResultSet基类:
package MyApp::Schema::ResultSet; use Moose; use MooseX::MarkAsMethods autoclean => 1; use MooseX::NonMoose; extends 'DBIx::Class::ResultSet'; __PACKAGE__->Meta->make_immutable; 1;
表my_table的示例ResultSet类:
package MyApp::Schema::ResultSet::MyTable; use Moose; use MooseX::MarkAsMethods autoclean => 1; extends 'MyApp::Schema::ResultSet'; sub oldest { my $self = shift; $self->search({},{order_by => {-ASC => 'date'}})->first; } __PACKAGE__->Meta->make_immutable; 1;
表my_table的示例结果类:
package MyApp::Schema::Result::MyTable; use Moose; use MooseX::MarkAsMethods autoclean => 1; extends 'MyApp::Schema::Result'; __PACKAGE__->table("my_table"); __PACKAGE__->add_columns( id => {data_type => "integer",is_auto_increment => 1},date => {data_type => "date"},); __PACKAGE__->set_primary_key("id"); __PACKAGE__->Meta->make_immutable; 1;