Mercurial > pub > Impl
annotate Lib/IMPL/Web/Application/Action.pm @ 170:b88b7fe60aa3
refactoring
author | sourcer |
---|---|
date | Tue, 24 May 2011 01:11:16 +0400 |
parents | 4267a2ac3d46 |
children | aaab45153411 |
rev | line source |
---|---|
52 | 1 package IMPL::Web::Application::Action; |
55 | 2 use strict; |
52 | 3 |
166 | 4 use parent qw(IMPL::Object IMPL::Object::Autofill); |
52 | 5 |
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
6 __PACKAGE__->PassThroughArgs; |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
7 |
52 | 8 use IMPL::Class::Property; |
9 | |
10 BEGIN { | |
11 public property application => prop_get | owner_set; | |
62 | 12 public property query => prop_get | owner_set; |
52 | 13 public property response => prop_get | owner_set; |
65 | 14 public property responseFactory => prop_get | owner_set; |
55 | 15 |
16 private property _entryPoint => prop_all; | |
17 } | |
18 | |
65 | 19 sub CTOR { |
20 my ($this) = @_; | |
21 | |
22 $this->responseFactory('IMPL::Web::Application::Response') unless $this->responseFactory; | |
23 $this->response( $this->responseFactory->new(query => $this->query) ); | |
24 } | |
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
25 |
55 | 26 sub Invoke { |
27 my ($this) = @_; | |
28 | |
29 if ($this->_entryPoint) { | |
30 $this->_entryPoint->(); | |
31 } else { | |
32 die new IMPL::InvalidOperationException("At least one handler is required"); | |
33 } | |
34 } | |
35 | |
65 | 36 sub ReinitResponse { |
37 my ($this) = @_; | |
38 | |
39 die new IMPL::InvalidOperationException("Response already sent") if $this->response->isHeaderPrinted; | |
40 | |
41 $this->response->Discard; | |
42 $this->response($this->responseFactory->new(query => $this->query)); | |
43 } | |
44 | |
55 | 45 sub ChainHandler { |
46 my ($this,$handler) = @_; | |
47 | |
48 my $delegateNext = $this->_entryPoint(); | |
49 | |
50 if (ref $handler eq 'CODE') { | |
56 | 51 $this->_entryPoint( sub { |
55 | 52 $handler->($this,$delegateNext); |
56 | 53 } ); |
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
54 } elsif (ref $handler and UNIVERSAL::isa($handler,'IMPL::Web::QueryHandler')) { |
56 | 55 $this->_entryPoint( sub { |
55 | 56 $handler->Invoke($this,$delegateNext); |
56 | 57 } ); |
58 } elsif ($handler and not ref $handler) { | |
59 | |
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
60 if (my $method = $this->can($handler) ) { |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
61 $this->_entryPoint( sub { |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
62 $method->($this,$delegateNext); |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
63 } ); |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
64 } else { |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
65 { |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
66 no strict 'refs'; |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
67 eval "require $handler; 1;" or die new IMPL::InvalidArgumentException("An invalid handler supplied",$handler,"Failed to load module") unless keys %{"${handler}::"}; |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
68 } |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
69 |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
70 if (UNIVERSAL::isa($handler,'IMPL::Web::QueryHandler')) { |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
71 $this->_entryPoint( sub { |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
72 $handler->Invoke($this,$delegateNext); |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
73 } ); |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
74 } else { |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
75 die new IMPL::InvalidArgumentException("An invalid handler supplied",$handler); |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
76 } |
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
77 } |
55 | 78 } else { |
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
79 die new IMPL::InvalidArgumentException("An invalid handler supplied",$handler); |
55 | 80 } |
81 | |
52 | 82 } |
83 | |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
84 sub cookie { |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
85 my ($this,$name,$rx) = @_; |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
86 |
149 | 87 $this->_launder(scalar( $this->query->cookie($name) ), $rx ); |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
88 } |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
89 |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
90 sub param { |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
91 my ($this,$name,$rx) = @_; |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
92 |
146 | 93 $this->_launder(scalar( $this->query->param($name) ), $rx ); |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
94 } |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
95 |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
96 sub _launder { |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
97 my ($this,$value,$rx) = @_; |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
98 |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
99 if ( $value ) { |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
100 if ($rx) { |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
101 if ( my @result = ($value =~ m/$rx/) ) { |
149 | 102 return @result > 1 ? \@result : $result[0]; |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
103 } else { |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
104 return undef; |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
105 } |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
106 } else { |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
107 return $value; |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
108 } |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
109 } else { |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
110 return undef; |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
111 } |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
112 } |
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
67
diff
changeset
|
113 |
52 | 114 1; |
115 | |
116 __END__ | |
117 | |
118 =pod | |
119 | |
67 | 120 =head1 NAME |
121 | |
122 C<IMPL::Web::Application::Action> - Обертка вокруг C<CGI> запроса. | |
123 | |
52 | 124 =head1 DESCRIPTION |
125 | |
67 | 126 C<[Infrastructure]> |
52 | 127 |
67 | 128 Определяет порядок выполнения запроса. Запрос выполняется последовательным вызовом |
129 цепочки обработчиков, при этом обработчики сами вызывают следующие. | |
130 Обработчики выполняются в порядке, обратном их добавлению. | |
52 | 131 |
132 Типичная цепочка может быть такой, в порядке добавления | |
133 | |
67 | 134 =begin code |
135 | |
136 IMPL::Web::QueryHandler::SecCallToMethod | |
137 IMPL::Web::QueryHandler::AuthenticateCookie | |
138 IMPL::Web::QueryHandler::PageFormat | |
139 | |
140 =end code | |
52 | 141 |
142 что приведет к следующей последовательности | |
143 | |
67 | 144 =begin code |
145 | |
146 # the application creates a new Action object | |
147 | |
148 my $action = $application->actionFactory->new( | |
149 action => $application, # the application passes self | |
150 query => $query # current CGI query | |
151 ); | |
152 | |
153 # forms query handlers stack | |
154 | |
155 $action->ChainHandler($_) foreach qw ( | |
156 IMPL::Web::QueryHandler::SecCallToMethod | |
157 IMPL::Web::QueryHandler::AuthenticateCookie | |
158 IMPL::Web::QueryHandler::PageFormat | |
159 ); | |
160 | |
161 # and finally invokes the action | |
162 | |
163 $action->Invoke() { | |
164 | |
165 # some internals | |
166 | |
167 IMPL::Web::QueryHandler::PageFormat->Invoke($action,$nextHandlerIsAuthHandler) { | |
168 | |
169 #some internals | |
170 | |
171 my $result = $nextHandlerIsAuthHandler() { | |
172 | |
173 # some internals | |
174 | |
175 IMPL::Web::QueryHandler::AuthenticateCookie->Invoke($action,$nextHandlerIsSecCall) { | |
176 | |
177 # some internals | |
178 # do auth and generate security $context | |
179 | |
180 # impersonate $context and call the next handler | |
181 return $context->Impersonate($nextHandlerIsSecCall) { | |
182 | |
183 # some internals | |
184 | |
185 IMPL::Web::QueryHandler::SecCallToMethod->Invoke($action,undef) { | |
186 | |
187 # next handler isn't present as it is the last hanler | |
188 | |
189 # some internals | |
190 # calculate the $method and the $target from CGI request | |
191 | |
52 | 192 IMPL::Security->AccessCheck($target,$method); |
193 return $target->$method(); | |
67 | 194 |
52 | 195 } |
67 | 196 |
52 | 197 } |
67 | 198 |
52 | 199 } |
200 } | |
67 | 201 |
202 # some intenals | |
203 # formatted output to $action->response->streamBody | |
52 | 204 } |
205 } | |
206 | |
67 | 207 =end code |
208 | |
52 | 209 или как альтернатива может быть еще |
210 | |
67 | 211 =begin code |
212 | |
213 IMPL::Web::QueryHandler::SecCallToMethod | |
214 IMPL::Web::QueryHandler::AuthenticateCookie | |
215 IMPL::Web::QueryHandler::Filter->new( target => IMPL::Transform::ObjectToJSON->new() , method => 'Transform') | |
216 IMLP::Web::QueryHandler::JSONFormat | |
217 | |
218 | |
219 =end code | |
52 | 220 |
221 В данной цепочке также происходит вызов метода, но его результат потом преобразуется | |
222 в простые структуры и передается JSON преобразователю. Таким образом модулю логики | |
223 не требуется знать о выходном формате, всю работу проделают дополнительные фильтры. | |
224 | |
67 | 225 =head1 MEMBERS |
226 | |
227 =head2 PROPERTIES | |
228 | |
229 =over | |
230 | |
231 =item C< [get] application> | |
232 | |
233 Экземпляр приложения создавшего текущий объект | |
234 | |
235 =item C< [get] query > | |
236 | |
237 Экземпляр C<CGI> запроса | |
238 | |
239 =item C< [get] response > | |
240 | |
241 Ответ на C<CGI> заспрос C<IMPL::Web::Application::Response> | |
242 | |
243 =item C< [get] responseFactory > | |
244 | |
245 Фабрика ответов на запрос, используется для создания нового ответа | |
246 либо при конструировании текущего объекта C<IMPL::Web::Application::Action>, | |
247 либо при вызове метода C<ReinitResponse> у текущего объекта. | |
248 | |
249 По умолчанию имеет значение C<IMPL::Web::Application::Response> | |
250 | |
251 =back | |
252 | |
253 =head2 METHODS | |
254 | |
255 =over | |
256 | |
257 =item C< ReinitResponse() > | |
258 | |
259 Отмена старого ответа C<response> и создание вместо него нового. | |
260 | |
261 Данная операция обычно проводится при обработке ошибок, когда | |
262 уже сформированный ответ требуется отменить. Следует заметить, | |
263 что эта операция не возможна, если ответ частично или полностью | |
264 отправлен клиенту. Тогда возникает исключение C<IMPL::InvalidOperationException>. | |
265 | |
266 =item C< ChainHandler($handler) > | |
267 | |
268 Добавляет новый обработчик в цепочку. Выполнение цепочки начинается с конца, | |
269 тоесть последний добавленный будет выполнен первым. | |
270 | |
271 =back | |
272 | |
56 | 273 =head1 HANDLERS |
274 | |
275 =head2 subroutines | |
276 | |
277 =over | |
278 | |
279 =item CODE ref | |
280 | |
281 Ссылка на процедуру может являться обработчиком, при этом функция будет вызвана с | |
282 двумя параметрами: ссылкой на action объект, и точкой входа следующего обработчика. | |
283 | |
284 =item Method Name | |
285 | |
286 Имя метода, передается в виде строки. У текущего объекта action ищется метод с | |
287 указанным именем, после чего используется ссылка на этот метод для вызова с двумя | |
288 параметрами: ссылкой на action объект, и точкой входа следующего обработчика. | |
289 | |
290 Получается вызов идентичный следующему C<< $action->MethodName($nextHandler) >>; | |
291 | |
292 =back | |
293 | |
67 | 294 =head2 C< IMPL::Web::QueryHandler > |
57 | 295 |
67 | 296 Любой объект наследованный от C< IMPL::Web::QueryHandler > может быть |
57 | 297 использован в качестве обработчика запроса |
298 | |
52 | 299 =cut |