Mercurial > pub > Impl
annotate Lib/IMPL/Web/Application/ControllerUnit.pm @ 170:b88b7fe60aa3
refactoring
author | sourcer |
---|---|
date | Tue, 24 May 2011 01:11:16 +0400 |
parents | 4267a2ac3d46 |
children | 59e5fcb59d86 |
rev | line source |
---|---|
133 | 1 use strict; |
110 | 2 package IMPL::Web::Application::ControllerUnit; |
166 | 3 use parent qw(IMPL::Object); |
110 | 4 |
5 use IMPL::Class::Property; | |
112 | 6 use IMPL::DOM::Transform::PostToDOM; |
7 use IMPL::DOM::Schema; | |
113 | 8 use Class::Inspector; |
9 use File::Spec; | |
133 | 10 use Sub::Name; |
112 | 11 |
12 use constant { | |
13 CONTROLLER_METHODS => 'controller_methods', | |
14 STATE_CORRECT => 'correct', | |
15 STATE_NEW => 'new', | |
16 STATE_INVALID => 'invalid' | |
17 }; | |
110 | 18 |
19 BEGIN { | |
20 public property action => prop_get | owner_set; | |
21 public property application => prop_get | owner_set; | |
22 public property query => prop_get | owner_set; | |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
142
diff
changeset
|
23 public property response => prop_get | owner_set; |
111 | 24 public property formData => prop_get | owner_set; |
25 public property formSchema => prop_get | owner_set; | |
26 public property formErrors => prop_get | owner_set; | |
110 | 27 } |
28 | |
170 | 29 my %publicProps = map {$_->Name , 1} __PACKAGE__->get_meta(typeof IMPL::Class::PropertyInfo); |
133 | 30 |
113 | 31 __PACKAGE__->class_data(CONTROLLER_METHODS,{}); |
32 | |
170 | 33 our @schemaInc; |
34 | |
110 | 35 sub CTOR { |
112 | 36 my ($this,$action,$args) = @_; |
110 | 37 |
38 $this->action($action); | |
39 $this->application($action->application); | |
40 $this->query($action->query); | |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
142
diff
changeset
|
41 $this->response($action->response); |
112 | 42 |
43 $this->$_($args->{$_}) foreach qw(formData formSchema formErrors); | |
44 } | |
45 | |
134 | 46 sub unitNamespace() { |
47 "" | |
48 } | |
49 | |
50 sub transactions { | |
51 my ($self,%methods) = @_; | |
52 | |
53 while (my ($method,$info) = each %methods) { | |
54 if ($info and ref $info ne 'HASH') { | |
55 warn "Bad transaction $method description"; | |
56 $info = {}; | |
57 } | |
58 | |
59 $info->{wrapper} = 'TransactionWrapper'; | |
60 $self->class_data(CONTROLLER_METHODS)->{$method} = $info; | |
61 } | |
62 } | |
63 | |
112 | 64 sub forms { |
65 my ($self,%forms) = @_; | |
66 | |
67 while ( my ($method,$info) = each %forms ) { | |
68 die new IMPL::Exception("A method doesn't exists in the controller",$self,$method) unless $self->can($method); | |
69 if ( not ref $info ) { | |
70 $self->class_data(CONTROLLER_METHODS)->{$method} = { | |
71 wrapper => 'FormWrapper', | |
72 schema => $info | |
73 }; | |
74 } elsif (ref $info eq 'HASH') { | |
75 die new IMPL::Exception("A schema must be specified",$self,$method) unless $info->{schema}; | |
76 | |
148
e6447ad85cb4
DOM objects now have a schema and schemaSource properties
wizard
parents:
146
diff
changeset
|
77 $info->{wrapper} = 'FormWrapper'; |
e6447ad85cb4
DOM objects now have a schema and schemaSource properties
wizard
parents:
146
diff
changeset
|
78 |
e6447ad85cb4
DOM objects now have a schema and schemaSource properties
wizard
parents:
146
diff
changeset
|
79 $self->class_data(CONTROLLER_METHODS)->{$method} = $info; |
112 | 80 } else { |
81 die new IMPL::Exception("Unsupported method information",$self,$method); | |
82 } | |
83 } | |
84 } | |
85 | |
110 | 86 sub InvokeAction { |
87 my ($self,$method,$action) = @_; | |
88 | |
112 | 89 if (my $methodInfo = $self->class_data(CONTROLLER_METHODS)->{$method}) { |
90 if (my $wrapper = $methodInfo->{wrapper}) { | |
91 return $self->$wrapper($method,$action,$methodInfo); | |
92 } else { | |
93 return $self->TransactionWrapper($method,$action,$methodInfo); | |
94 } | |
110 | 95 } else { |
96 die new IMPL::InvalidOperationException("Invalid method call",$self,$method); | |
97 } | |
111 | 98 } |
99 | |
133 | 100 sub MakeParams { |
101 my ($this,$methodInfo) = @_; | |
102 | |
103 my $params; | |
104 if ($params = $methodInfo->{parameters} and ref $params eq 'ARRAY') { | |
146 | 105 return map $this->ResolveParam($_,$methodInfo->{inflate}{$_}), @$params; |
133 | 106 } |
107 return(); | |
108 } | |
109 | |
110 sub ResolveParam { | |
146 | 111 my ($this,$param,$inflate) = @_; |
133 | 112 |
113 if ( $param =~ /^::(\w+)$/ and $publicProps{$1}) { | |
114 return $this->$1(); | |
115 } else { | |
146 | 116 my $value; |
117 if ( my $rx = $inflate->{rx} ) { | |
118 $value = $this->action->param($param,$rx); | |
119 } else { | |
120 $value = $this->query->param($param); | |
121 } | |
122 | |
123 if (my $method = $inflate->{method}) { | |
124 $value = $this->$method($value); | |
125 } | |
126 return $value; | |
133 | 127 } |
128 } | |
129 | |
112 | 130 sub TransactionWrapper { |
131 my ($self,$method,$action,$methodInfo) = @_; | |
132 | |
133 my $unit = $self->new($action); | |
133 | 134 return $unit->$method($unit->MakeParams($methodInfo)); |
112 | 135 } |
136 | |
137 sub FormWrapper { | |
113 | 138 my ($self,$method,$action,$methodInfo) = @_; |
139 | |
140 my $schema = $self->loadSchema($methodInfo->{schema}); | |
141 | |
142 my $process = $action->query->param('process') || 0; | |
143 my $form = $methodInfo->{form} | |
144 || $action->query->param('form') | |
145 || $schema->selectSingleNode('ComplexNode')->name | |
146 or die new IMPL::Exception('No situable form name could be determined',$self,$method); | |
112 | 147 |
113 | 148 my %result; |
112 | 149 |
113 | 150 my $transform = IMPL::DOM::Transform::PostToDOM->new( |
151 undef, | |
152 $schema, | |
153 $form | |
154 ); | |
155 | |
138 | 156 $result{formName} = $form; |
113 | 157 $result{formSchema} = $schema; |
126 | 158 $result{formData} = $transform->Transform($action->query); |
159 | |
112 | 160 |
113 | 161 if ($process) { |
162 $result{formErrors} = $transform->Errors->as_list; | |
163 if ($transform->Errors->Count) { | |
164 $result{state} = STATE_INVALID; | |
165 } else { | |
166 $result{state} = STATE_CORRECT; | |
167 my $unit = $self->new($action,\%result); | |
127
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
168 |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
169 eval { |
133 | 170 $result{result} = $unit->$method($unit->MakeParams($methodInfo)); |
127
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
171 }; |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
172 if (my $err = $@) { |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
173 $result{state} = STATE_INVALID; |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
174 if (eval { $err->isa(typeof IMPL::WrongDataException) } ) { |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
175 $result{formErrors} = $err->Args; |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
176 } else { |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
177 die $err; |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
178 } |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
179 } |
113 | 180 } |
181 } else { | |
182 $result{state} = STATE_NEW; | |
183 } | |
112 | 184 |
113 | 185 return \%result; |
186 } | |
187 | |
188 sub loadSchema { | |
189 my ($self,$name) = @_; | |
170 | 190 |
191 foreach my $path (map File::Spec->catfile($_,$name) ,@schemaInc) { | |
192 return IMPL::DOM::Schema->LoadSchema($path) if -f $path; | |
193 } | |
113 | 194 |
170 | 195 die new IMPL::Exception("A schema isn't found", $name); |
196 } | |
197 | |
198 sub unitSchema { | |
199 my ($self) = @_; | |
200 | |
201 my $class = ref $self || $self; | |
202 | |
203 my @parts = split(/:+/, $class); | |
204 | |
205 my $file = pop @parts; | |
206 $file = "${file}.schema.xml"; | |
207 | |
208 foreach my $inc ( @schemaInc ) { | |
209 my $path = File::Spec->catfile($inc,@parts,$file); | |
126 | 210 |
170 | 211 return IMPL::DOM::Schema->LoadSchema($path) if -f $path; |
126 | 212 } |
170 | 213 |
214 return undef; | |
112 | 215 } |
216 | |
134 | 217 sub discover { |
218 my ($this) = @_; | |
219 | |
220 my $methods = $this->class_data(CONTROLLER_METHODS); | |
221 | |
222 my $namespace = $this->unitNamespace; | |
223 (my $module = typeof $this) =~ s/^$namespace//; | |
133 | 224 |
134 | 225 my %smd = ( |
226 module => [grep $_, split /::/, $module ], | |
227 ); | |
133 | 228 |
134 | 229 while (my ($method,$info) = each %$methods) { |
230 my %methodInfo = ( | |
231 name => $method | |
232 ); | |
160 | 233 $methodInfo{parameters} = [ grep /^[^\:]/, @{ $info->{parameters} } ] if ref $info->{parameters} eq 'ARRAY'; |
134 | 234 push @{$smd{methods}},\%methodInfo; |
235 } | |
236 return \%smd; | |
133 | 237 } |
238 | |
134 | 239 __PACKAGE__->transactions( |
240 discover => undef | |
241 ); | |
133 | 242 |
111 | 243 1; |
244 | |
245 __END__ | |
246 | |
247 =pod | |
248 | |
249 =head1 NAME | |
250 | |
251 C<IMPL::Web::Application::ControllerUnit> - базовый класс для обработчика транзакций в модели контроллера. | |
252 | |
253 =head1 DESCRIPTION | |
254 | |
113 | 255 Классы, наследуемые от данного класса называется пакетом транзакций. Часть методов в таком классе |
256 объявляются как транзакции при помощи методов C<transaction>, C<form>. | |
111 | 257 |
258 Перед выполнением транзакции создается экземпляр объекта, в рамках которого будет выполнена транзакция. | |
259 Для этого вызывается метод C<InvokeAction($method,$action)>, который создает/восстанавливает контекст | |
260 транзакции. | |
261 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
262 Транзакции на данный момент делятся на простые и формы. Различные типы транзакций выполняются при помощи |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
263 различных оберток (C<TransactionWrapper> и C<FormWrapper>). Каждая обертка отвечает за конструирование |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
264 экземпляра объекта и вызов метода для выполнения транзакции, а также за возврат результата выполнения. |
111 | 265 |
266 =head2 Простые транзакции | |
267 | |
268 Простые транзакции получаю только запрос, без предварительной обработки, и возвращенный результат напрямую | |
269 передается пользователю. | |
270 | |
271 =head2 Формы | |
272 | |
273 При использовании форм запрос предварительно обрабатывается, для получения DOM документа с данными формы. | |
274 Для постороенния DOM документа используется схема. При этом становятся доступны дополнительные свойства | |
275 C<formData>, C<formSchema>, C<formErrors>. | |
276 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
277 Результат выполнения транзакции не возвращается наверх напрямую, а включается в структуру, которая |
111 | 278 выглядит следующим образом |
279 | |
280 =begin code | |
281 | |
282 { | |
283 state => '{ new | correct | invalid }', | |
284 result => $transactionResult, | |
285 formData => $formDOM, | |
286 formSchema => $formSchema, | |
287 formErrors => @errors | |
288 } | |
289 | |
290 =end code | |
291 | |
292 =over | |
293 | |
294 =item C<state> | |
295 | |
296 Состояние верификации формы. | |
297 | |
298 =over | |
299 | |
300 =item C<new> | |
301 | |
302 Первоначальное содержимое формы, оно может быть некорректным, но это нормально. | |
303 В данном состоянии транзакция обычно не выполняется. | |
304 | |
305 =item C<correct> | |
306 | |
307 Данные формы корректны, транзакция выполнена, и ее результат доступен через поле C<result> | |
308 | |
309 =item C<invalid> | |
310 | |
311 Содержимое формы не прошло верификацию, ошибки доступны через поле C<formErrors>. Транзакция | |
312 не выполнялась. | |
313 | |
314 =back | |
315 | |
316 =item C<result> | |
317 | |
318 Результат выполнения транзакции, если конечно таковая выполнялась. | |
319 | |
320 =item C<formData> | |
321 | |
322 ДОМ документ с данными формами. Документ существует всегда, не зависимо от его корректности, | |
323 может быть использован для построения формы, уже заполненную параметрами. | |
324 | |
325 =item C<formSchema> | |
326 | |
327 Схема данных формы, может использоваться для построения динамических форм. | |
328 | |
329 =item C<formErrors> | |
330 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
331 Ссылка на массив с ошибками при проверки формы. |
111 | 332 |
333 =back | |
334 | |
335 =head1 MEMBERS | |
336 | |
337 =over | |
338 | |
339 =item C<[get] application> | |
340 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
341 Объект приложения, которое обрабатывает запрос. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
342 |
111 | 343 =item C<[get] query> |
344 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
345 Текущий запрос. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
346 |
111 | 347 =item C<[get] response> |
348 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
349 Текущий ответ. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
350 |
111 | 351 =item C<[get] formData> |
352 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
353 C<IMPL::DOM::Document> документ с данныим, если данный запрос является формой. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
354 |
111 | 355 =item C<[get] formSchema> |
356 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
357 C<IMPL::DOM::Schema> документ со схемой формы данного запроса. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
358 |
111 | 359 =item C<[get] formErrors> |
360 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
361 Ошибки верификации данных, если таковые были. Обычно при наличии ошибок в форме, транзакция |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
362 не выполняется, а эти ошибки передаются в ответ. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
363 |
111 | 364 =item C<InvokeAction($method,$action)> |
365 | |
366 Конструирует контекст выполнения транзакции, может быть переопределен для конструирования контекста по | |
112 | 367 своим правилам. |
368 | |
369 =item C<TransactionWrapper($method,$action,$methodInfo)> | |
370 | |
371 Обертка для конструирования простых транзакций, может быть переопределен для конструирования контекста по | |
372 своим правилам. | |
373 | |
374 =item C<FormWrapper($method,$action,$methodInfo)> | |
375 | |
376 Обертка для конструирования форм, может быть переопределен для конструирования контекста по | |
377 своим правилам. | |
111 | 378 |
134 | 379 =item C<discover()> |
380 | |
381 Метод, опубликованный для вызова контроллером, возвращает описание методов в формате C<Simple Module Definition>. | |
382 | |
383 =begin code | |
384 | |
385 # SMD structure | |
386 { | |
387 module => ['Foo','Bar'], | |
388 methods => [ | |
389 { | |
390 name => 'search', | |
391 parameters => ['text','limit'] #optional | |
392 } | |
393 ] | |
394 } | |
395 | |
396 =end code | |
397 | |
111 | 398 =back |
399 | |
400 =head1 EXAMPLE | |
401 | |
402 =begin code | |
403 | |
404 package MyBooksUnit; | |
405 use strict; | |
166 | 406 use parent qw(IMPL::Web::Application::ControllerUnit); |
111 | 407 |
408 __PACKAGE__->PassThroughArgs; | |
409 | |
134 | 410 sub unitDataClass { 'My::Books' } |
411 | |
412 __PACKAGE__->transactions( | |
413 find => { | |
414 parameters => [qw(author)] | |
415 }, | |
416 info => { | |
417 parameters => [qw(id)] | |
418 } | |
419 ); | |
111 | 420 __PACKAGE__->forms( |
421 create => 'books.create.xml' | |
422 ); | |
423 | |
424 sub find { | |
134 | 425 my ($this,$author) = @_; |
111 | 426 |
134 | 427 return $this->ds->find({author => $author}); |
111 | 428 } |
429 | |
430 sub info { | |
134 | 431 my ($this,$id) = @_; |
111 | 432 |
134 | 433 return $this->ds->find({id => $id}); |
111 | 434 } |
435 | |
436 sub create { | |
437 my ($this) = @_; | |
438 | |
439 my %book = map { | |
134 | 440 $_->nodeName, $_->nodeValue |
441 } $this->formData->selectNodes([qw(author_id title year ISBN)]); | |
111 | 442 |
134 | 443 return $this->ds->create(\%book); |
111 | 444 } |
445 | |
446 =end code | |
447 | |
448 =cut |