be7a1d4ece47dd2940bd1508348157d9ff55873b
[kivitendo-erp.git] / SL / System / ResourceCache.pm
1 package SL::System::ResourceCache;
2
3 use strict;
4 use File::stat;
5 use File::Find;
6
7 our @paths = qw(image css);
8 our $cache;
9
10 sub generate_data {
11   return if $cache;
12
13   $cache = {};
14
15   File::Find::find(sub {
16     $cache->{ $File::Find::name =~ s{^\./}{}r } = stat($_);
17   }, @paths);
18 }
19
20 sub get {
21   my ($class, $file) = @_;
22   no warnings 'once';
23
24   return stat($file) if ($::dispatcher // { interface => 'cgi' })->{interface} eq 'cgi';
25
26   $class->generate_data;
27   $cache->{$file};
28 }
29
30 1;
31
32
33 __END__
34
35 =encoding utf-8
36
37 =head1 NAME
38
39 SL::System::ResourceCache - provides access to resource files without having to access the filesystem all the time
40
41 =head1 SYNOPSIS
42
43   use SL::System::ResourceCache;
44
45   SL::System::ResourceCache->get($filename);
46
47 =head1 DESCRIPTION
48
49 This will stat() all files in the configured paths at startup once, so that
50 subsequent calls can use the cached values. Particularly useful for icons in
51 the menu, which would otherwise generate a few hundred file sytem accesses per
52 request.
53
54 The caching will not happen in CGI and script environments.
55
56 =head1 FUNCTIONS
57
58 =over 4
59
60 =item * C<get FILENAME>
61
62 If the file exists, returns a L<File::stat> object. If it doesn't exists, returns undef.
63
64 =back
65
66 =head1 BUGS
67
68 None yet :)
69
70 =head1 TODO
71
72 Make into instance cache and keep it as system wide object
73
74 =head1 AUTHOR
75
76 Sven Schöling E<lt>sven.schoeling@googlemail.comE<gt>
77
78 =cut
79