Newer Older
63 lines | 1.12kb
added EXPERIMENTAL DBIx::Cus...
Yuki Kimoto authored on 2012-01-25
1
package DBIx::Custom::Pool;
2
use Object::Simple -base;
3
use Carp 'croak';
4
use Digest::MD5 'md5_hex';
5

            
6
has count => 5;
7

            
8
sub prepare {
9
  my ($self, $cb) = @_;
10
  
11
  my $count = $self->count;
12
  for (my $i = 0; $i < $count; $i++) {
13
    my $dbi = $cb->();
14
    
15
    my $id = $self->_id;
16
    
17
    $self->{_pool}{$id} = $dbi;
18
  }
19
  return $self;
20
}
21

            
22
sub get {
23
  my $self = shift;
24
  
25
  my @ids = keys %{$self->{_pool}};
26
  croak "Pool is empty" unless @ids;
27
  my $id = $ids[0];
28
  my $dbi = delete $self->{_pool}{$id};
29
  $self->{_borrow}{$id} = 1;
30
  $dbi->{_pool_id} = $id;
31
  return $dbi;
32
}
33

            
34
sub back {
35
  my ($self, $dbi) = @_;
36
  my $id = $dbi->{_pool_id};
37
  return unless ref $dbi && defined $id;
38
  croak "This DBIx::Custom object is already returned back"
39
    if $self->{_pool}{$id};
40
  delete $self->{_borrow}{$id};
41
  $self->{_pool}{$id} = $dbi;
42
  
43
  return $self;
44
}
45

            
46
sub _id {
47
  my $self = shift;
48
  my $id;
49
  do { $id = md5_hex('c' . time . rand 999) }
50
    while $self->{_pool}->{$id} || $self->{_borrow}->{$id};
51
  return $id;
52
}
53

            
54
1;
55

            
56
=head1 NAME
57

            
58
DBIx::Custom::Pool
59

            
60
=head1 DESCRIPTION
61

            
62
DBI Pool. this module is very experimental.
63