Mercurial > pub > Impl
annotate Lib/IMPL/Config.pm @ 184:7525ea9a071a
IMPL::Web::View::TTLoader tests
author | sergey |
---|---|
date | Thu, 29 Mar 2012 01:54:20 +0400 |
parents | d1676be8afcc |
children | 4d0e1962161c |
rev | line source |
---|---|
49 | 1 package IMPL::Config; |
2 use strict; | |
3 use warnings; | |
4 | |
165 | 5 use parent qw(IMPL::Object::Accessor IMPL::Object::Serializable IMPL::Object::Autofill); |
49 | 6 |
7 __PACKAGE__->PassThroughArgs; | |
8 | |
170 | 9 use File::Spec(); |
10 | |
49 | 11 use IMPL::Class::Member; |
12 use IMPL::Class::PropertyInfo; | |
13 use IMPL::Exception; | |
14 | |
15 use IMPL::Serialization; | |
16 use IMPL::Serialization::XmlFormatter; | |
17 | |
170 | 18 our $ConfigBase ||= ''; |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
19 |
49 | 20 sub LoadXMLFile { |
21 my ($self,$file) = @_; | |
22 | |
23 my $class = ref $self || $self; | |
24 | |
25 my $serializer = new IMPL::Serializer( | |
26 Formatter => new IMPL::Serialization::XmlFormatter( | |
27 IdentOutput => 1, | |
28 SkipWhitespace => 1 | |
29 ) | |
30 ); | |
31 | |
32 open my $hFile,'<',$file or die new IMPL::Exception("Failed to open file",$file,$!); | |
33 | |
34 my $obj; | |
35 eval { | |
36 $obj = $serializer->Deserialize($hFile); | |
37 }; | |
38 | |
39 if ($@) { | |
40 my $e=$@; | |
41 die new IMPL::Exception("Can't load the configuration file",$file,$e); | |
42 } | |
43 return $obj; | |
44 } | |
45 | |
46 sub SaveXMLFile { | |
47 my ($this,$file) = @_; | |
48 | |
49 my $serializer = new IMPL::Serializer( | |
50 Formatter => new IMPL::Serialization::XmlFormatter( | |
51 IdentOutput => 1, | |
52 SkipWhitespace => 1 | |
53 ) | |
54 ); | |
55 | |
56 open my $hFile,'>',$file or die new IMPL::Exception("Failed to open file",$file,$!); | |
57 | |
58 $serializer->Serialize($hFile, $this); | |
59 } | |
60 | |
61 sub xml { | |
62 my $this = shift; | |
63 my $serializer = new IMPL::Serializer( | |
64 Formatter => new IMPL::Serialization::XmlFormatter( | |
65 IdentOutput => 1, | |
66 SkipWhitespace => 1 | |
67 ) | |
68 ); | |
69 my $str = ''; | |
70 open my $hFile,'>',\$str or die new IMPL::Exception("Failed to open stream",$!); | |
71 | |
72 $serializer->Serialize($hFile, $this); | |
73 | |
74 undef $hFile; | |
75 | |
76 return $str; | |
77 } | |
78 | |
79 sub save { | |
80 my ($this,$ctx) = @_; | |
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
81 |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
82 my $val; |
49 | 83 |
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
84 $val = $this->rawGet($_) and $ctx->AddVar($_ => $val) foreach map $_->Name, $this->get_meta( |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
85 'IMPL::Class::PropertyInfo', |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
86 sub { |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
87 $_->Access == IMPL::Class::Member::MOD_PUBLIC and |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
88 $_->canGet; |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
89 }, |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
60
diff
changeset
|
90 1); |
49 | 91 } |
92 | |
58 | 93 sub spawn { |
170 | 94 my ($this,$file) = @_; |
179 | 95 unless ($file) { |
96 ($file = ref $this || $this) =~ s/:+/./g; | |
97 $file .= ".xml"; | |
98 } | |
170 | 99 return $this->LoadXMLFile( File::Spec->catfile($ConfigBase,$file) ); |
58 | 100 } |
101 | |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
102 sub get { |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
103 my $this = shift; |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
104 |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
105 if (@_ == 1) { |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
106 my $obj = $this->SUPER::get(@_); |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
107 return UNIVERSAL::isa($obj,'IMPL::Config::Activator') ? $obj->activate : $obj; |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
108 } else { |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
109 my @objs = $this->SUPER::get(@_); |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
110 return map UNIVERSAL::isa($_,'IMPL::Config::Activator') ? $_->activate : $_, @objs ; |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
111 } |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
112 } |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
113 |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
114 sub rawGet { |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
115 my $this = shift; |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
116 return $this->SUPER::get(@_); |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
117 } |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
118 |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
119 sub Exists { |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
120 $_[0]->SUPER::get($_[1]) ? 1 : 0; |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
121 } |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
122 |
49 | 123 1; |
124 __END__ | |
125 | |
126 =pod | |
127 | |
73 | 128 =head1 NAME |
129 | |
180 | 130 C<IMPL::Config> - базовый класс для настраиваемого приложения. |
73 | 131 |
132 =head1 SYNOPSIS | |
49 | 133 |
73 | 134 =begin code |
135 | |
136 # define application | |
137 | |
138 package MyApp; | |
165 | 139 use parent qw(IMPL::Config); |
49 | 140 |
141 use IMPL::Class::Property; | |
142 use IMPL::Config::Class; | |
143 | |
144 BEGIN { | |
145 public property SimpleString => prop_all; | |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
146 public property DataSource => prop_all; |
49 | 147 } |
148 | |
149 sub CTOR { | |
150 my $this = shift; | |
73 | 151 |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
152 $this->DataSource( |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
153 new IMPL::Config::Activator( |
73 | 154 factory => 'MyDataSource', |
155 parameters=>{ | |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
156 host => 'localhost', |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
157 user => 'dbuser' |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
158 } |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
159 ) |
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
160 ) unless $this->Exists('DataSource'); |
49 | 161 } |
162 | |
73 | 163 # using application object |
58 | 164 |
73 | 165 my $app = spawn MyApp('default.xml'); |
58 | 166 |
167 $app->Run(); | |
168 | |
73 | 169 =end code |
170 | |
180 | 171 Ниже приведен пример файла C<default.xml> содержащего настройки приложения |
73 | 172 |
173 =begin code xml | |
174 | |
175 <app type='MyApp'> | |
176 <SimpleString>The application</SimpleString> | |
177 <DataSource type='IMPL::Config::Activator'> | |
178 <factory>MyDataSourceClass</factory> | |
179 <parameters type='HASH'> | |
180 <host>localhost</host> | |
181 <user>dbuser</user> | |
182 </parameters> | |
183 </DataSource> | |
184 </app> | |
185 | |
186 =end code xml | |
187 | |
49 | 188 =head1 DESCRIPTION |
189 | |
73 | 190 C<[Serializable]> |
191 | |
192 C<[Autofill]> | |
193 | |
165 | 194 C<use parent IMPL::Object::Accessor> |
73 | 195 |
180 | 196 Базовый класс для приложений. Использует подход, что приложение |
197 является объектом, состояние которого предтавляет собой конфигурацию, | |
198 а методы - логику. | |
73 | 199 |
180 | 200 Данный класс реализует функционал десериализации (и сериализации) экземпляра |
201 приложения из XML документа. Для этого используется механизм C<IMPL::Serialization>. | |
202 При этом используются опции C<IMPL::Serialization::XmlFormatter> C<IdentOutput> и | |
203 C<SkipWhitespace> для записи документа в легко читаемом виде. | |
73 | 204 |
180 | 205 Поскольку в результате восстановления приложения восстанавливаются все элементы |
206 из файла конфигурации, то это может потребовать значительных ресурсов для | |
207 создания частей, которые могут никогда не понадобиться. Например, не требуется инициализация | |
208 источника данных для передачи пользователю статических данных, сохраненных на диске. | |
73 | 209 |
180 | 210 Для решения этой проблемы используются специальные объекты C<IMPL::Config::Activator>. |
73 | 211 |
180 | 212 Если у приложения описано свойство, в котором хранится C<IMPL::Config::Activator>, то |
213 при первом обращении к такому свойству, будет создан объект вызовом метода | |
214 C<< IMPL::Config::Activator->activate() >> и возвращен как значение этого свойства. | |
215 Таким образом реализуется прозрачная отложенная активация объектов, что позволяет | |
216 экономить ресурсы. | |
49 | 217 |
218 =head1 MEMBERS | |
219 | |
220 =over | |
221 | |
73 | 222 =item C<[static] LoadXMLFile($fileName) > |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
223 |
180 | 224 Создает из XML файла C<$fileName> экземпляр приложения |
49 | 225 |
73 | 226 =item C<SaveXMLFile($fileName)> |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
227 |
180 | 228 Сохраняет приложение в файл C<$fileName> |
73 | 229 |
230 =item C<[get] xml > | |
49 | 231 |
180 | 232 Сохраняет конфигурацию приложения в XML строку. |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
233 |
73 | 234 =item C<[static,operator] spawn($file)> |
49 | 235 |
180 | 236 Синоним для C<LoadXMLFile>, предполагается использование как оператора. |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
237 |
73 | 238 =item C<rawGet($propname,...)> |
239 | |
180 | 240 Метод для получения значений свойств приложения. Данный метод позволяет избежать |
241 использование активации объектов через C<IMPL::Config::Activator>. | |
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
58
diff
changeset
|
242 |
49 | 243 =back |
244 | |
245 =cut |