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