【发布时间】:2018-04-02 18:46:39
【问题描述】:
我正在尝试为我的 Perl 6 预算应用程序设计一个“数据访问层”。目标是让用户将各种购买存储在 SQLite 数据库中,我的应用程序将生成各种报告,告知用户消费习惯。
但是,我在做一个“正确的”数据访问层时遇到了麻烦。事实上,我想知道这个应用程序是否值得。无论如何,我想学习如何正确地设计它“面向对象”。
我知道我希望我的类是表,并且类的属性对应于表中的行。就目前而言,我的代码根本不使用类属性,但仍然可以正常工作。
有任何理由使用类属性吗?我有looked up a few resources,其中大部分是Java,我很难翻译到Perl 6。它看起来不必要地复杂,但我怀疑这是因为我不明白这种设计模式的原因。
1 #!/usr/bin/env perl6
2
3 use v6;
4 use DBIish;
5
6 constant DB = 'budgetpro.sqlite3';
7 my $dbh = DBIish.connect('SQLite', database => DB);
8
9 $dbh.do('drop table if exists Essential');
10
11 sub create-schema {
12 $dbh.do(qq:to/SCHEMA/);
13 create table if not exists Essential(
14 id integer primary key not null,
15 name varchar not null,
16 price numeric(5,2) not null,
17 quant integer not null,
18 desc varchar not null,
19 date timestamp default (datetime('now'))
20 );
21 SCHEMA
22 }
23
24 create-schema;
25
26 class Item {
27 has $!table = 'Essential';
28 has $.name is rw;
29 has $.price is rw;
30 has $.quant is rw;
31 has Str $.desc;
32
33 method insert($name, $price, $quant, $desc) {
34 my $sth = $dbh.prepare(qq:to/INSERT/);
35 insert into $!table (name, price, quant, desc) values (?,?,?,?)
36 INSERT
37 $sth.execute($name, $price, $quant, $desc);
38 }
39
40 multi method select-all {
41 my $sth = $dbh.prepare(qq:to/SELECT/);
42 select * from $!table
43 SELECT
44 $sth.execute;
45 $sth.allrows(:array-of-hash);
46 }
47
48 multi method select-all($begin, $end) {
49 my $sth = $dbh.prepare(qq:to/SELECT/);
50 select * from $!table where date >= ? and date <= ?
51 SELECT
52 $sth.execute($begin, $end);
53 $sth.allrows(:array-of-hash);
54 }
55
56
57 # Needs accurate implementation
58 multi method total-cost($table, $begin?, $end?) {
59 sub total-price {
60 my $sth = $dbh.prepare(qq:to/SUM/);
61 select sum(price) from $table
62 SUM
63 $sth.execute;
64 $sth.allrows[0];
65 }
66 sub total-quant {
67 my $sth = $dbh.prepare(qq:to/SUM/);
68 select sum(quant) from $table
69 SUM
70 $sth.execute;
71 $sth.allrows[0];
72 }
73 return (total-quant[0] * total-price[0]);
74 }
75
76 multi method total-cost($table, $begin, $end) {
77 my $sth = $dbh.prepare(qq:to/SUM/);
78 select sum(price) from $table where date >= ? and date <= ?
79 SUM
80 $sth.execute($begin, $end);
81 $sth.allrows;
82 }
83 }
84
85 class Essential is Item {}
86
87 class Savings is Item {}
88
89 class Personal is Item {}
编辑:使用示例-
my ($name, $price, $quant, $desc) = 'Apple', 0.99, 2, 'Delicious apple';
my $item = Essential.new;
$item.insert($name, $price, $quant, $desc);
say $item.select-all;
输出:
({date => 2018-04-02 18:59:46, desc => A delicious apple, id => 1, name => Apple, price => 5.99, quant => 2})
【问题讨论】: