如何覆盖 Perl 的 Class::DBI 中自动生成的访问器?
我按照 http://wiki.class-dbi.com/wiki/Overriding_autogenerate_accessors
我想在将 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(@_);
}
但它不起作用:
my $company = Hosting::Company->insert({ Name => 'Test', Url => 'http://http://url' });
print $company->Url, "\n";
显示:
http://http://url
我希望 Class:DBI 邮件列表仍然存在!
I followed the example at http://wiki.class-dbi.com/wiki/Overriding_autogenerated_accessors
I want to modify the URL before it is inserted to the database:
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 URL 访问器中,您检查参数是否传递给该方法。 但是您没有传递任何内容,因此访问器除了调用 _Url_accessor() 之外什么也不做。 您可能应该首先调用 _Url_accessor,然后修改结果:
如果您想在 URL 进入数据库之前更改 URL,我想您必须在您的类中提供 normalize_column_values,并且每次插入时都会调用它。
In you URL accessor, you check whether a parameter was passed to that method. But you aren't passing anyhting in so the accessor will do nothing but call _Url_accessor(). You should probably call _Url_accessor first and then modify the result:
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.
重写访问器不会更改
insert
。 处理数据标准化的最佳方法是重写normalize_column_values()
。 但曼尼是对的,你的访问器坏了。PS CDBI 邮件列表仍然活跃,只是没有看到太多帖子。 大多数已转移到 DBIx::Class。
Overriding an accessor does not change
insert
. The best way to handle data normalization is to overridenormalize_column_values()
. But Manni is right, your accessor is busted.PS The CDBI mailing list is still active, just hasn't seen much posting. Most have moved on to DBIx::Class.