DBIx :: Class抽象父ResultSet

时间:2012-05-27 02:35:09

标签: perl dbix-class

我试图找出一个干净的OO方式来实现我遇到的DBIx :: Class问题。我有一个User表,其中包含所有用户共有的信息。每个用户还可以拥有许多不同的类,每个类都有自己独特的必需信息。例如,用户可以是管理员和作者。管理员和作者类有单独的表。

我希望能够创建一个公共基类来访问用户对象中的所有类。所以一个名为Schema :: UserClass的基类和两个名为Schema :: UserClass :: Admin和Schema :: UserClass :: Author的子类。我希望能做的是:

# Get current user
my $user = MyApp->get_user();

# Get user classes
my @classes = $user->classes->all();
for my $class (@classes) {
    # Print class name
    print $class->name;
}

此处提出了类似的问题:http://dbix-class.35028.n2.nabble.com/OO-advice-do-a-subclass-do-something-else-td5614176.html。但是我认为解决方案是子部分,因为它需要为每个类添加新的关系。

我没有看到如何在知道所有子类的情况下与基类建立关系。任何帮助将非常感激。

1 个答案:

答案 0 :(得分:0)

我找到的解决方案也不是很好,但确实有效。如果我有时间,我可以在CPAN模块中合并此代码,使其更漂亮。

package ParentSchema::Result::Class;

use strict;
use warnings;

use parent 'DBIx::Class::Core';

__PACKAGE__->add_columns(
  "user_id",
  {
    data_type => "integer",
    size => 32,
    is_foreign_key => 1,
    is_auto_increment => 0,
    is_nullable => 0,
    default_value => '',
  },
);

# stuff common to all schemas

__PACKAGE__->belongs_to(
  "user",
  "Schema::Result::User",
  { 'foreign.id' => "self.user_id" },
  { is_deferrable => 1, on_delete => "CASCADE", on_update => "CASCADE" },
);

1;

package Schema::Result::Class::Author

use strict;
use warnings;

use parent 'ParentSchema::Class';

__PACKAGE__->table('class_author');

# class spesific stuff

__PACKAGE__->meta->make_immutable;

1;


package Schema::Result::User;

use strict;
use warnings;

use parent 'DBIx::Class::Core';

use Module::Pluggable::Object;
use String::CamelCase qw(decamelize);

__PACKAGE__->add_columns(
  "id",
  {
    data_type => "integer",
    size => 32,
    is_auto_increment => 1,
    is_nullable => 0,
    default_value => '',
  },
);

my $class_path = 'Schema::Result::Class';

my $mp = Module::Pluggable::Object->new(
    search_path => [ $class_path ]
);
my @class_plugins = $mp->plugins;

foreach my $class (@class_plugins) {
  (my $name = $class) =~ s/^\Q${class_path}\E//;
  __PACKAGE__->might_have(
    decamelize($name),
    $class,
    { "foreign.user_id" => "self.id" },
    { cascade_copy => 0, cascade_delete => 0 },
  );
}

__PACKAGE__->meta->make_immutable;

1;