简体   繁体   English

如何在Perl的Class :: DBI中覆盖自动生成的访问器?

[英]How do I override autogenerated accessors in Perl's Class::DBI?

I followed the example at http://wiki.class-dbi.com/wiki/Overriding_autogenerated_accessors 我按照http://wiki.class-dbi.com/wiki/Overriding_autogenerated_accessors上的示例进行了操作

I want to modify the URL before it is inserted to the database: 我想在将URL插入数据库之前修改它:

package Hosting::Company;
use base 'Class::DBI';

 my $class = __PACKAGE__;

$class->table('Companies');
$class->columns(Primary => 'CompanyId');
$class->columns(Others => qw/Name Url Comment/);

sub Url {
my $self = shift;

    # modify URL.
    if (@_) {
        $_[0] = 'aaaaaaaaaaaa';
        # return $self->_Url_accessor('aaaaaaaaaaaa'); - doesn't work either
    }

    # Back to normal Class::DBI 
    return $self->_Url_accessor(@_);
}

But it doesn't work: 但它不起作用:

my $company = Hosting::Company->insert({ Name => 'Test', Url => 'http://http://url' });
print $company->Url, "\n";

Shows: 显示:

http://http://url

I wish the Class:DBI mailing list were still alive! 我希望Class:DBI邮件列表还活着!

In you URL accessor, you check whether a parameter was passed to that method. 在URL访问器中,检查参数是否已传递给该方法。 But you aren't passing anyhting in so the accessor will do nothing but call _Url_accessor(). 但是你没有传递任何东西,所以访问者除了调用_Url_accessor()之外什么都不做。 You should probably call _Url_accessor first and then modify the result: 你应该首先调用_Url_accessor然后修改结果:

sub Url {
    my $self = shift;

    # Was there a param passed in?
    if ( @_ ) {
         # Do you really want to modify it here?
         return $self->_Url_accessor(@_);
    }
    else {
        my $url = $self->_Url_accessor();
        # mangle result here:
        $url = 'aaaaaaaaa';
        return $url;
     }
}

If you want to change the URL before it even goes in the database, I guess you must provide a normalize_column_values in your class and this will be called each time an insert is made. 如果你想在进入数据库之前更改URL,我想你必须在你的类中提供normalize_column_values,每次插入时都会调用它。

Overriding an accessor does not change insert . 覆盖访问器不会更改insert The best way to handle data normalization is to override normalize_column_values() . 处理数据规范化的最佳方法是覆盖normalize_column_values() But Manni is right, your accessor is busted. 但曼尼是对的,你的存取者被破坏了。

PS The CDBI mailing list is still active, just hasn't seen much posting. PS CDBI邮件列表仍然活跃,只是没有看到太多帖子。 Most have moved on to DBIx::Class . 大多数人已转向DBIx :: Class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM