Mercurial > pub > Impl
annotate Lib/IMPL/Web/Application.pm @ 129:e4f15cbc3f1a
Fixed utf-8 problem
| author | wizard |
|---|---|
| date | Tue, 15 Jun 2010 20:12:58 +0400 |
| parents | 6dd659f6f66c |
| children | 06a34c197b05 |
| rev | line source |
|---|---|
| 49 | 1 package IMPL::Web::Application; |
| 2 use strict; | |
| 3 use warnings; | |
| 4 | |
|
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
59
diff
changeset
|
5 use base qw(IMPL::Config IMPL::Object::Singleton); |
| 58 | 6 |
| 7 require IMPL::Web::Application::Action; | |
| 8 require IMPL::Web::Application::Response; | |
| 9 | |
| 49 | 10 use IMPL::Class::Property; |
| 57 | 11 use CGI; |
| 49 | 12 |
|
60
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
59
diff
changeset
|
13 __PACKAGE__->PassThroughArgs; |
|
b0c068da93ac
Lazy activation for the configuration objects (final concept)
wizard
parents:
59
diff
changeset
|
14 |
| 49 | 15 BEGIN { |
| 52 | 16 public property handlerError => prop_all; |
| 67 | 17 public property actionFactory => prop_all; |
|
59
0f3e369553bd
Rewritten property implementation (probably become slower but more flexible)
wizard
parents:
58
diff
changeset
|
18 public property handlersQuery => prop_all | prop_list; |
| 65 | 19 public property responseCharset => prop_all; |
| 73 | 20 public property security => prop_all; |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
62
diff
changeset
|
21 public property options => prop_all; |
| 97 | 22 public property fetchRequestMethod => prop_all; |
| 49 | 23 } |
| 24 | |
| 62 | 25 sub CTOR { |
| 26 my ($this) = @_; | |
| 27 | |
| 67 | 28 $this->actionFactory('IMPL::Web::Application::Action') unless $this->actionFactory; |
| 65 | 29 $this->responseCharset('utf-8') unless $this->responseCharset; |
| 97 | 30 $this->fetchRequestMethod(\&defaultFetchRequest) unless $this->fetchRequestMethod; |
| 31 $this->handlerError(\&defaultHandlerError) unless $this->handlerError; | |
| 62 | 32 } |
| 33 | |
| 49 | 34 sub Run { |
| 35 my ($this) = @_; | |
| 36 | |
| 58 | 37 while (my $query = $this->FetchRequest()) { |
| 38 | |
| 67 | 39 my $action = $this->actionFactory->new( |
| 62 | 40 query => $query, |
| 58 | 41 application => $this, |
| 65 | 42 ); |
| 43 | |
| 97 | 44 eval { |
| 45 $action->response->charset($this->responseCharset); | |
| 46 | |
| 47 $action->ChainHandler($_) foreach $this->handlersQuery; | |
| 48 | |
| 49 $action->Invoke(); | |
| 50 | |
| 51 $action->response->Complete; | |
| 52 }; | |
| 53 if ($@) { | |
|
99
6dd659f6f66c
Minor changes, DOM schema is in development (in the aspect of a forms)
wizard
parents:
97
diff
changeset
|
54 my $e = $@; |
| 129 | 55 # we are expecting this method to be safe otherwise we can trust nothing in this wolrd |
|
99
6dd659f6f66c
Minor changes, DOM schema is in development (in the aspect of a forms)
wizard
parents:
97
diff
changeset
|
56 $this->handlerError()->($this,$action,$e); |
| 97 | 57 } |
| 49 | 58 } |
| 59 } | |
| 60 | |
| 97 | 61 sub FetchRequest { |
| 62 my ($this) = @_; | |
| 63 | |
| 64 if( ref $this->fetchRequestMethod eq 'CODE' ) { | |
| 65 return $this->fetchRequestMethod->($this); | |
| 66 } else { | |
| 67 die new IMPL::Exception("Unknown fetchRequestMethod type",ref $this->fetchRequestMethod); | |
| 68 } | |
| 69 } | |
| 70 | |
| 57 | 71 { |
| 72 my $hasFetched = 0; | |
| 73 | |
| 97 | 74 sub defaultFetchRequest { |
| 129 | 75 my ($this) = @_; |
| 57 | 76 return undef if $hasFetched; |
| 77 $hasFetched = 1; | |
| 129 | 78 my $query = CGI->new(); |
| 79 $query->charset($this->responseCharset); | |
| 80 return $query; | |
| 57 | 81 } |
| 82 } | |
| 83 | |
| 97 | 84 sub defaultHandlerError { |
| 85 my ($this,$action,$e) = @_; | |
| 86 warn $e; | |
| 87 if ( eval { $action->ReinitResponse(); 1; } ) { | |
| 88 $action->response->contentType('text/plain'); | |
| 89 $action->response->charset($this->responseCharset); | |
| 90 $action->response->status(500); | |
| 91 my $hout = $action->response->streamBody; | |
| 92 print $hout $e; | |
| 93 $action->response->Complete(); | |
| 94 } | |
| 95 } | |
| 96 | |
| 49 | 97 1; |
| 98 | |
| 52 | 99 __END__ |
| 100 | |
| 49 | 101 =pod |
| 102 | |
| 103 =head1 SYNOPSIS | |
| 104 | |
| 67 | 105 =begin code |
| 106 | |
| 49 | 107 require MyApp; |
| 67 | 108 |
| 109 my $instance = spawn MyApp('app.config'); | |
| 110 | |
| 111 $instance->Run(); | |
| 112 | |
| 113 =end code | |
| 49 | 114 |
| 115 =head1 DESCRIPTION | |
| 116 | |
| 73 | 117 C< use base qw( IMPL::Config IMPL::Object::Singleton )> |
| 118 | |
| 49 | 119 Зкземпляр приложения содержит в себе глобальные настройки, реализует контроллер запросов, |
| 52 | 120 в качестве источника запросов используется CGI или иной совместимый модуль. |
| 49 | 121 |
| 52 | 122 Процесс обработки запроса состоит из следующих частей |
| 49 | 123 |
| 67 | 124 =over |
| 125 | |
| 126 =item 1 | |
| 127 | |
| 128 Получение cgi запроса | |
| 129 | |
| 130 =item 2 | |
| 52 | 131 |
| 67 | 132 Создание объекта C<IMPL::Web::Application::Action> |
| 52 | 133 |
| 67 | 134 =item 3 |
| 52 | 135 |
| 67 | 136 Формирование цепочки вызовов при помощи C<< IMPL::Web::Application::Action->ChainHandler >> |
| 137 | |
| 138 =item 4 | |
| 139 | |
| 140 Выполнение запроса C<< IMPL::Web::Application::Action->Invoke >> | |
| 49 | 141 |
| 142 =cut | |
| 67 | 143 |
| 144 Также приложение поддерживает отложенное создание объектов, которые по первому обращению | |
| 145 к свойствам. Это реализовано в базовом классе C< IMPL::Configuration >. Для настройки | |
| 146 активаторов можно использовать свойство C<options>, в которое должен быть помещен хеш | |
| 147 со ссылками на активаторы, см. пример ниже C<CONFIGURATION>. | |
| 148 | |
| 149 =head2 CONFIGURATION | |
| 150 | |
| 151 Ниже приведен пример конфигурации приложения | |
| 152 | |
| 153 =begin code xml | |
| 154 | |
| 155 <?xml version="1.0" encoding="UTF-8"?> | |
| 156 <Application id='app' type="Test::Web::Application::Instance"> | |
| 157 | |
| 158 <!-- Begin custom properties --> | |
| 159 <name>Sample application</name> | |
| 160 <dataSource type='IMPL::Config::Activator' id='ds'> | |
| 161 <factory>IMPL::Object</factory> | |
| 162 <parameters type='HASH'> | |
| 163 <db>data</db> | |
| 164 <user>nobody</user> | |
| 165 </parameters> | |
| 166 </dataSource> | |
| 167 <securityMod type='IMPL::Config::Activator'> | |
| 168 <factory>IMPL::Object</factory> | |
| 169 <parameters type='HASH'> | |
| 170 <ds refid='ds'/> | |
| 171 </parameters> | |
| 172 </securityMod> | |
| 173 <!-- End custom properties --> | |
| 174 | |
| 175 <!-- direct access to the activators --> | |
| 176 <options type="HASH"> | |
| 177 <dataSource refid='ds'/> | |
| 178 </options> | |
| 179 | |
| 180 <!-- Set default output encoding, can be changed due query handling --> | |
| 181 <responseCharset>utf-8</responseCharset> | |
| 182 | |
| 183 <!-- Actions creation configuration --> | |
| 184 <actionFactory type="IMPL::Object::Factory"> | |
| 185 | |
| 186 <!-- Construct actions --> | |
| 187 <factory>IMPL::Web::Application::Action</factory> | |
| 188 <parameters type='HASH'> | |
| 189 | |
| 190 <!-- with special responseFactory --> | |
| 191 <responseFactory type='IMPL::Object::Factory'> | |
| 192 | |
| 193 <!-- Where resopnses have a special streamOut --> | |
| 194 <factory>IMPL::Web::Application::Response</factory> | |
| 195 <parameters type='HASH'> | |
| 196 | |
| 197 <!-- in memory dummy output instead of STDOUT --> | |
| 198 <streamOut>memory</streamOut> | |
| 199 | |
| 200 </parameters> | |
| 201 </responseFactory> | |
| 202 </parameters> | |
| 203 </actionFactory> | |
| 204 | |
| 205 <!-- Query processing chain --> | |
| 206 <handlersQuery type="IMPL::Object::List"> | |
| 207 <item type="IMPL::Web::QueryHandler::PageFormat"> | |
| 208 <templatesCharset>cp1251</templatesCharset> | |
| 209 </item> | |
| 210 </handlersQuery> | |
| 211 </Application> | |
| 212 | |
| 213 =end code xml | |
| 214 | |
| 73 | 215 =head1 MEMBERS |
| 216 | |
| 217 =over | |
| 218 | |
| 219 =item C<[get,set] handlerError> | |
| 220 | |
| 221 Обработчик который будет вызван в случае возникновения необработанной ошибки | |
| 222 в процессе работы приложения. После чего приложение корректно завершается. | |
| 223 | |
| 224 =item C<[get,set] actionFactory> | |
| 225 | |
| 226 Фабрика объектов, которая используется приложением, для создания объектов | |
| 227 типа C<IMPL::Web::Application::Action> при обработки C<CGI> запросов. | |
| 228 | |
| 229 =begin code | |
| 230 | |
| 231 my $action = $this->actionFactory->new( | |
| 232 query => $query, | |
| 233 application => $this, | |
| 234 ); | |
| 235 | |
| 236 =end code | |
| 237 | |
| 97 | 238 =item C< [get,set] fetchRequestMethod > |
| 239 | |
| 240 Метод получения CGI запроса. Возвращает C<CGI> объект следующего запроса, если | |
| 241 запросов больше нет, то возвращает C<undef>. По-умолчанию использует C<defaultFetchRequest>. | |
| 242 | |
| 243 Может быть как ссылкой на функцию, так и объектом типа C<IMPL::Web::Application::RequestFetcher>. | |
| 244 | |
| 73 | 245 =item C< [get,set,list] handlersQuery > |
| 246 | |
| 247 Список обработчиков запросов, которые будут переданы созданному объекту-действию. | |
| 248 | |
| 249 =item C< [get,set] responseCharset> | |
| 250 | |
| 251 Кодировка ответа клиенту. | |
| 252 | |
| 253 =item C< [get,set] security > | |
| 254 | |
| 255 Объект C<IMPL::Web::Security>, для работы с инфраструктурой безопасности. | |
| 256 | |
| 257 =item C< [get,set] options > | |
| 258 | |
| 259 Обычно ссылка на хеш с настраиваемыми объектами, используется для возможности | |
| 260 програмной настройки активаторов, т.к. напрямую через свойства приложения получить | |
| 261 к ним доступ не получится. | |
| 262 | |
| 263 =back | |
| 264 | |
| 265 =cut |
