3.5 Data presentation patterns in WEB

Lecture



One of the most impressive changes that have occurred to corporate applications over the past few years is the emergence of user interfaces in the style of Web browsers. They brought with them a number of advantages: they eliminated the need to use a special client software layer, generalized and unified access procedures and simplified the problem of designing Web applications.

The functions of the Web server are to interpret the URL of the request and transfer control to the appropriate program (the option when the WEB server reads from the disk and sends the client a regular file is not considered). There are two main forms of presentation of a Web server program - a script (script) and a server page (serverpage).

A script consists of functions or methods designed to handle HTTP requests. Typical examples are CGI scripts and Java servlets. Such a program is able to do almost everything the same as a traditional application.

The script is often divided into sub-programs and uses third-party services. It retrieves data from the web page by checking the HTTP request string object and extracting regular expressions from it; the simplicity of implementing such functions using Perl has earned the latter the fame of one of the most adequate tools for developing CGI scripts. In other cases, for example, when using Java servlets, the programmer gains access to the request information through the keyword interface, which is often much more convenient. The result of the Web server is another — the reply line — a string formed by a script involving the usual functions of stream output.

The task of generating HTML code through streaming output commands is not very attractive for programmers, and non-programmers can’t do it at all, although they would gladly take on Web-design using other tools. This naturally leads to the server page model, where the functions of the program are reduced to returning a chunk of text data. The page contains HTML text with "interspersed" executable code. Such an approach, implemented, for example, in PHP, ASP and JSP, is especially convenient if minor additional text processing is required considering the user's reaction.

Since the script model is better suited for interpreting requests, and the server page layout is used for formatting answers, it is quite reasonable to use them together. In fact, this is a rather old idea, first implemented in user interfaces based on the model-view-controller pattern.

The solution is widely used, but it is often interpreted incorrectly (this is especially true for applications written before the advent of the Web). The main reason is the ambiguous interpretation of the term "controller". It is used in many contexts, and it is given a very different meaning, sometimes completely contrary to the one found in the MVC decision. That is why, speaking of this solution, they prefer to use the phrase input controller (input controller).

The input controller accepts the request and extracts information from it. It then passes the business logic to the appropriate model object, which accesses the data source and performs the actions specified in the request, including gathering the information necessary for the response. Upon completion of the functions, he transfers control to the input controller, which, analyzing the result obtained, decides on the choice of the answer option. The control and the corresponding data are transferred to the view. The interaction of the input view controller is often not in the form of direct calls, but through the mediation of some object of the HTTP session, which serves to transfer data in both directions.

The main argument in favor of applying the model-view-controller solution is that it provides for the complete separation of the model from the web-view. This simplifies the ability to modify existing and add new views. And placing logic in separate objects of the transaction script (Transaction Script) and domain model (Domain Model) facilitates their testing. This is especially important when the server page is used as a view. Here comes the turn of the practical application of the second version of the interpretation of the term "controller". In many versions of the user interface, view objects are separated from domain objects by an intermediate layer of Application Controller objects, the purpose of which is to control the flow of application functions and select the order in which the interface screens are displayed. The application controller looks like a part of the presentation layer or as an independent “layer” between the presentation level and the subject area. Application controllers can be implemented independently of any private representation, and then they can be reused for different representations.

Application controllers are needed by no means to all systems. They are convenient when an application is distinguished by a wealth of logic regarding the order of playback of interface screens and navigation between them, or the absence of a simple relationship between pages and entities of the subject area. When the order of the pages is irrelevant, the need to use application controllers practically does not arise. Here is a simple test to determine whether it is advisable to use application controllers: if the flow of system functions is controlled by the machine, the answer is positive, and if the user is negative.

3.5.1 Model-View-Controller Pattern

The pattern distributes user interface processing between three participants.

A typical model-view controller solution is one of the most frequently cited (and, unfortunately, misinterpreted). It originally appeared as the infrastructure developed by Trigve Reenskaug for the Smalltalk platform in the late 1970s. Since then, it has played a significant role in the development of a variety of infrastructures and formed the basis for a number of user interface design concepts.

Operating principle

A typical model-view-controller solution involves the allocation of three separate roles. A model is an object that provides some domain information. The model has no visual interface, it contains all the data and behavior that are not related to the user interface. In an object-oriented context, the most “pure” form of the model is the object object domain model (Domain Model). A transaction scenario (Transaction Script) can also be considered as a model, if it does not contain any logic related to the user interface. Such a definition does not greatly expand the concept of a model, but fully corresponds to the distribution of roles in the model solution under consideration.

3.5 Data presentation patterns in WEB

Figure 3.20 MVC Pattern Structure

The view displays the contents of the model by means of a graphical interface. Thus, if our model is a customer object, the corresponding view can be a frame with a bunch of controls or an HTML page filled with customer information. View functions are only to display information on the screen. All information changes are processed by the third "participant" of our system - the controller. The controller receives input from the user, performs operations on the model, and indicates to the view the need for an appropriate update. In this regard, the graphical interface can be viewed as a combination of a view and a controller.

Speaking about the typical MVC solution, it is impossible not to emphasize two fundamental types of separation: the separation of the representation from the model and the separation of the controller from the representation.

Separating the presentation from the model is one of the fundamental principles of software design. The presence of such a division is very important for several reasons.

  • Representation and model belong to completely different fields of programming. While developing the presentation, you are thinking about the mechanisms of the user interface and how to make the application interface as user friendly as possible. In turn, when working with a model, your attention is focused on business policies and, possibly, on interaction with the database. Obviously, when developing models and representations, different (completely different!) Libraries are used. In addition, most developers specialize in only one of these areas.
  • Users want the same information to be displayed in different ways, depending on the situation. Separating the view from the model allows you to develop for the same model code several views, or rather, several completely different interfaces. This approach is most pronounced in the case when the same model can be represented using a thick client, a web browser, a remote API, or a command line interface. Even within the same Web interface in different places of an application, different pages may correspond to the same customer.
  • Objects that do not have a visual interface are much easier to test than objects with an interface. Separating the view from the model makes it easy to test all domain logic without resorting to such “terrible” things as scripting tools to support the graphical user interface.

The key point in separating the representation from the model is the direction of dependencies: the representation depends on the model, but the model does not depend on the representation. Model programmers should generally not be aware of which representation will be used. This greatly facilitates the development of the model and at the same time simplifies the subsequent addition of new views.

In addition, this means that changing the view does not require changing the model. This principle is closely related to a common problem. When using a thick client with multiple dialog boxes, several views of the same model can be on the screen at the same time. If the user makes changes to the model through a single view, these changes should be reflected in all other views. In order to make this possible in the absence of a bidirectional dependency, it is necessary to implement a typical solution Observer. In this case, the view will play the role of "observer" for the model: as soon as the model is changed, the view generates the corresponding event and all other views update their content.

The separation of the controller from the view does not play such an important role as the previous type of separation. Indeed, ironically, in almost all Smalltalk versions, the division into controller and presentation was not carried out. A classic example of the need for such a separation is the support of editable and non-editable behavior. This can be achieved with one view and two controllers (for two use cases), where controllers are the strategies used by the view. Meanwhile, in practice, in most systems, only one controller corresponds to each representation; therefore, the separation between them is not carried out.

This solution was remembered only when Web interfaces appeared, where the separation of the controller from the presentation turned out to be extremely useful. The fact that most user interface infrastructures did not divide into presentation and controller led to many misinterpretations of the MVC pattern. Yes, the presence of a model and presentation is obvious, but where is the controller? Many have decided that the controller is located between the model and the view, as in the Application Controller. This misconception further aggravated the fact that the word "controller" appears in both names. Meanwhile, despite all the positive qualities of an application controller, it is not at all like an MVC controller.

Purpose

As already noted, MVC consists of two types of separation. Separating the presentation from the model is one of the fundamental principles on which all software design rests, and it can only be neglected when it comes to very simple systems in which the model does not have any real behavior at all. As soon as non-visualized logic appears in the application, separation becomes extremely necessary. Unfortunately, in many user interface infrastructures, it is rather difficult to implement such a separation, and where it’s easy, they forget about it anyway.

Separating the view from the controller is not so important, so I recommend holding it only when you really need it. Such a need practically does not arise in systems with thick clients, but in the Web interfaces the separation of the controller is very useful. Most of the typical solutions considered here for designing web applications are based on this principle.

3.5.2 Page Controller Pattern

Page Controller. An object that processes a request to a specific web page or to perform a specific action on a web site.

3.5 Data presentation patterns in WEB

Figure 3.21. Structure of the Page Controller Pattern

Most Internet users have ever come across static HTML pages. When a site visitor requests a static page, it sends the name and path to the HTML document stored on this server to the Web server. The key point here is that each page of the Web site is presented on the server as a separate document. With dynamic pages, the situation is far from simple because of the more complex relationships between pathnames and the corresponding files. Despite this, a simple model in which one path corresponds to one document processing a request can be applied here.

A typical page controller solution assumes a separate controller for each logical page of the Web site. This controller can be the page itself (as is often the case in server page environments) or a separate object corresponding to this page.

Operating principle

At the heart of the page controller is the idea of ​​creating components that will act as controllers for each page of the Web site. In practice, the number of controllers does not always exactly correspond to the number of pages, because sometimes when clicking on a link, pages with different dynamic content open. More precisely, the controller is required for each action, which implies a click on a button or a hyperlink.

The page controller can be implemented as a script (CGI script, servlet, etc.) or server pages (ASP, PHP, JSP, etc.). Using a server page usually involves a combination of a page controller in a single file and a Template View. This is good for a template view, but not very suitable for a page controller, since it makes it very difficult to structure this component correctly. This problem is not so important if the page is used only for simple display of information. However, if the use of the page assumes the presence of logic related to the extraction of user data or the choice of a view to display the results, the server page can be filled with the nightmarish code of a “scriptlet”, i.e. embedded script. To avoid such problems, you can use a helper object. Upon receiving a request, the server page calls an auxiliary object to process all the available logic. Depending on the situation, the auxiliary object may return control to the server’s original page or refer to another server page to act as a presentation. In this case, the request handler is the server page, but most of the controller logic is enclosed in an auxiliary object.

A possible alternative to the described approach is to implement the handler and controller as a script. In this case, when a request comes in, the Web server transfers control to the script; the script performs all the actions assigned to the controller, and then displays the results obtained using the desired view.

The following are the main responsibilities of a page controller.

  • Analyze the URL and extract the data entered by the user into the appropriate forms to collect all the information necessary to perform the action.
  • Create model objects and call their methods necessary for data processing. All the necessary data from the HTTP request must be transferred to the model so that its objects are completely independent of this request.
  • Determine the view that should be used to display the results, and transfer to it the necessary information received from the model.

The page controller does not have to be a single class, but all controller classes can use the same auxiliary objects. This is especially useful if there should be several handlers on the Web server that perform similar tasks. In this case, the use of an auxiliary object avoids duplication of code.

If necessary, some URLs can be processed using server pages, and others using scripts. Those URLs that do not have or almost no controller logic are well handled using server pages, because the latter are a simple mechanism that is convenient for understanding and making changes. All other addresses that require more complex logic to process require the use of scripts.

Purpose

When deciding how to handle requests to a website, you need to decide which controller should use a page controller or a request controller (Front Controller). The page controller is simpler to use and is a natural structuring mechanism in which specific actions are handled by the corresponding server pages or script classes. The query controller is much more complicated, but it has a lot of various advantages, many of which are extremely important for Web sites with a complex navigation system.

The page controller is good to use for sites with fairly simple controller logic. In this case, most URLs can be processed using

server pages, and more complex cases - with the use of auxiliary objects.

If the controller logic is fairly simple, using a query controller will incur unnecessary costs. There are frequent situations when some requests to a Web site are processed using page controllers, while others are using request controllers, especially when developers refactor elements from one controller to another. In fact, these typical solutions work well together.

3.5.3 Front Controller Pattern

Query controller (Front Controller). A controller that handles all requests to the web server.

3.5 Data presentation patterns in WEB

Figure 3.22 Structure of the Front Controller pattern

Processing requests to Web sites with a complex structure involves the implementation of a large number of similar actions. This is a security check, providing support for internationalization, and opening special views for specific categories of users. If the input controller's behavior is scattered across several objects, it will duplicate most of the code. In addition, it will make it much more difficult to change the behavior of the controller at run time.

A typical solution to the query controller combines all actions for processing queries in one place, distributing their execution through a single handler object. Typically, this object implements a common behavior that can be changed at run time using decorators. To execute a particular request, the handler calls the appropriate command object.

Operating principle

The request controller processes all requests coming to the website, and usually consists of two parts: a web processor and a command hierarchy. A Web handler is an object that performs the actual receipt of a POST or GET request sent to the Web server. It extracts the necessary information from the URL and input data of the request, then decides what action must be initiated, and delegates its execution to the appropriate team (Fig. 3.23).

A web handler is usually implemented as a class, not a server page, since it does not generate any responses. Commands are also classes, not server pages; moreover, they do not need to be aware of the presence of the Web environment, despite the fact that they often receive information from HTTP requests. In most cases, a Web handler is a fairly simple program whose functions are to select the necessary command.

Team selection can occur statically or dynamically. Static command selection involves parsing the URL and applying conditional logic, and dynamic - extracting some standard URL fragment and dynamically creating an instance of the command class.

3.5 Data presentation patterns in WEB

Figure 3.23 The principle of the query controller

The advantages of static command selection are the use of explicit code, the availability of compile-time checks, and the high flexibility of possible spelling options for URLs. In turn, the use of a dynamic approach allows you to add new commands without requiring changes to the Web handler.

When dynamically selecting commands, the command class name can be placed directly into the URL address or you can use the properties file that will bind the URL addresses to the command class names. Of course, this will require the creation of an additional file of properties, however, it will allow you to easily and unconditionally change the names of the classes without looking at all the Web pages on the server.

Purpose

The query controller has a more complex structure than its obvious rival - the page controller To be given the attention of developers, the query controller must have at least a few advantages, and they, of course, have them.

First, the Web server must be configured to use only one request controller; the rest of the work of distributing requests will be done by the web handler. This will greatly facilitate the configuration of the Web server. Using dynamic command selection allows you to add new commands without any changes. In addition, dynamic commands facilitate portability, as you are only required to register a handler in the server settings. Since to execute each request, new instances of command classes are created, you do not have to worry about their functioning in separate threads. This will avoid all the hassles associated with multi-threaded programming; nevertheless, you will have to watch out for the lack of sharing of other objects,such as model objects.

The most frequently cited advantage of the query controller is the ability to implement common code that is somehow duplicated in multiple page controllers. Nevertheless, many forget that the general behavior of the latter with no less success can be made in the superclass of page controllers.

There is only one query controller, which makes it easy to change its behavior at run time with the help of numerous decorators. Decorators can be used to perform authentication, code selection, support internationalization, etc. Moreover, they can be added not only using the settings file, but also directly while the server is running.

3.5.4 Template View Pattern

View by template (Template View). Converts query results to HTML format by embedding markers in an HTML page.

Writing a program that generates HTML code is much more difficult than it might seem at first glance. Although modern programming languages ​​cope with the creation of text much better than in the old days, the creation and concatenation of string constructs is still associated with a lot of inconvenience. This problem is not so terrible, if the text is not too much, however, the creation of a whole HTML page may require a lot of "savage" manipulations of the text.

Для редактирования статических HTML-страниц (тех, содержимое которых не изменяется от запроса к запросу) можно использовать замечательные текстовые редакторы, работающие по принципу WYSIWYG (What You See Is What You Get — что видишь на экране, то и получишь при печати). Даже тем, кто предпочитает самые примитивные редакторы, набирать текст и дескрипторы намного приятнее, чем заниматься конкатенацией строк в коде программы.

3.5 Data presentation patterns in WEB

Рисунок 3.24 Структура паттерна Template View

Основные трудности связаны с созданием динамических Web-страниц — тех, которые принимают результаты выполнения какого-нибудь запроса (например, к базе данных) и внедряют их в код HTML. Содержимое такой страницы меняется с каждым запросом, а потому обыкновенные редакторы HTML здесь бессильны.

The most convenient way to create a dynamic Web page is to construct a conventional static page and then insert special markers into it that can be converted into function calls that provide dynamic information. Since the static part of the page acts as a kind of template, a typical solution is called a template presentation.

Operating principle

The basic idea behind the typical solution is a template presentation — inserting markers into the text of a finished static HTML page. When you call up a page to service a query, these tokens will be replaced with the results of some calculations (for example, the results of executing queries to the database). This scheme allows you to create a static part of the page using conventional tools, such as text editors, working on the principle of WYSIWYG, and does not require knowledge of programming languages. To obtain dynamic information, markers refer to individual programs.

The template presentation is used by a variety of software tools. Thus, your task is not so much to develop this solution yourself, but to learn how to use it effectively and to get acquainted with possible alternatives.

Insert markers

Существует несколько способов внедрения маркеров в HTML-страницу. Один из них - это использование HTML-подобных дескрипторов. Данный способ хорошо подходит для редакторов, работающих по принципу WYSIWYG, поскольку они распознают элементы, заключенные в угловые скобки (<>), как специальное содержимое и поэтому игнорируют их либо обращаются с ними иначе, чем с обычным текстом. Если дескрипторы удовлетворяют правилам форматирования языка XML, для работы с полученным документом можно использовать средства XML (разумеется, при условии, что результирующий документ HTML является документом XHTML).

Another way to embed dynamic content is to insert special text markers into the body of the page. In this case, the WYSIWYG text editors will perceive the inserted marker as plain text. Of course, the contents of the markers will not change, but may be subjected to a variety of intrusive operations, such as spell checking. However, this method eliminates the confusing HTML / XML syntax.

Some development environments contain sets of ready-made markers, but more and more platforms allow the developer to define their own descriptors and markers according to the needs of specific applications.

Одной из наиболее популярных форм представления по шаблону является страница сервера (serverpage) - ASP, JSP или PHP. Вообще говоря, страницы сервера - это нечто большее, чем представление по шаблону, поскольку они позволяют внедрять в страницу элементы программной логики, называемые скриптлетами (scriptlets). Однако, скриплеты в трудно назвать удачным решением. Наиболее очевидный недостаток внедрения в страницу сервера множества скриптлетов состоит в том, что ее могут редактировать исключительно программисты. Данная проблема особенно критична, если проектированием страницы занимаются графические дизайнеры. Однако самые существенные недостатки скриптлетов связаны с тем, что страница - далеко не самый подходящий модуль для программы. Даже при использовании объектно-ориентированных языков программирования внедрение кода в текст страницы лишает вас возможности применять многие средства структурирования, необходимые для построения модулей как в объектно-ориентированном, так и в процедурном стиле.

However, it is much more unpleasant that the introduction of a large number of scriptlets into a page leads to the “mixing” of layers of the corporate application. If the domain logic is launched directly on the server pages, it is practically indestructible and, at the same time, can easily lead to duplication of logic on other server pages.

Auxiliary object

Чтобы избежать использования скриптлетов, каждой странице можно назначить собственный вспомогательный объект (helper object). Этот объект будет содержать в себе всю фактическую логику домена, а сама страница - только вызовы вспомогательного объекта, что значительно упростит структуру страницы и максимально приблизит ее к "чистой" форме представления по шаблону. Более того, это обеспечит возможность "разделения труда", при котором непрограммисты смогут спокойно заняться редактированием страницы, а программисты - сосредоточиться на разработке вспомогательного объекта. В зависимости от используемого средства, все "шаблонное" содержимое страницы зачастую можно свести к набору HTML/XML - дескрипторов, что повысит согласованность страницы и сделает ее более пригодной для поддержки стандартными средствами.

The described scheme seems simple and quite trustworthy. However, as always, there are a few but. The simplest markers are those that receive information from the rest of the system and put this information in the right place on the page. Such markers can be easily converted into method calls of an auxiliary object, the result of which is text (or something that can be easily converted into text). This text is placed in the specified place on the page.

Conditional mapping

Much more difficult to implement the conditional behavior of the page. The simplest example of conditional behavior is when the result of a query is displayed only if the value of the conditional expression is true. This behavior can be implemented using conditional descriptors like

locale=' US'>текст >

рекомендуется использовать дескриптор вида

< locale includes = " US ">текст locale>

Итерация

Похожие проблемы связаны с итерацией по коллекциям объектов. Если вы хотите отобразить таблицу, где каждая строка будет соответствовать пункту заказа, вам понадобится реализовать конструкцию, которая позволит легко отображать сведения по каждой строке. В данном примере практически невозможно избежать итерации по дескриптору коллекций, однако обычно она выполняется довольно легко.

Разумеется, набор доступных дескрипторов ограничивается используемой средой разработки. Некоторые среды разработки предоставляют фиксированный набор дескрипторов, которых может оказаться недостаточно для реализации описанных выше приемов. Тем не менее в большинстве сред разработки набор доступных дескрипторов более обширен, а некоторые платформы даже позволяют создавать собственные библиотеки дескрипторов.

Обработка страницы

Как следует из названия, главной функцией типового решения представление по шаблону является выполнение роли представления в системе MVC. В большинстве корпоративных систем представление по шаблону должно выступать исключительно в качестве представления. В более простых системах его можно использовать как контроллер, а возможно, и как модель. Если представление по шаблону выполняет еще какие-либо функции, помимо функций представления, необходимо тщательно следить за тем, чтобы реализацию этих функций обеспечивал вспомогательный объект, а не страница сервера. Выполнение обязанностей контроллера и модели подразумевает наличие программной логики, которая, как и всякая другая программная логика, должна находиться во вспомогательном объекте.

Система, связанная с применением шаблонов, требует дополнительной обработки Web-сервером. Эта обработка может выполняться посредством компиляции страницы сразу после ее создания, компиляции страницы при поступлении первого запроса или же интерпретации страницы при поступлении каждого запроса. Последний вариант, очевидно, является неудачным, особенно если обработка страницы занимает определенное время.

Работая с представлением по шаблону, следует обращать внимание на исключения. Если исключение срабатывает "по пути" к Web-контейнеру, оно может прервать обработку страницы и привести к появлению в окне обозревателя весьма странного содержимого. Понаблюдайте, как Web-сервер обрабатывает исключения. Если он делает что-то не то, рекомендую обрабатывать все исключения самому, перехватывая их во вспомогательном классе (еще одна причина, по которой следует избегать скриптлетов).

Использование сценариев

Хотя наиболее популярной формой представления по шаблону были и остаются страницы сервера, в случае необходимости их можно заменить сценариями. Главное при написании такого сценария - избежать конкатенации строк, используя вызовы функций, которые будут возвращать необходимые дескрипторы (это особенно хорошо демонстрируют сценарии CGI). Данный прием позволит создавать сценарий на привычном языке программирования, избегая досадных "вкраплений" в программную логику в виде функций вывода строк на экран.

Purpose

Основными альтернативами для реализации представления в MVC являются представление по шаблону и представление с преобразованием (Transform View,). Преимущество представления по шаблону состоит в том, что оно позволяет оформлять представление в соответствии со структурой страницы. Данная возможность весьма привлекательна для тех, кто не умеет программировать. В частности, она позволяет воплотить в жизнь идею, когда графический дизайнер занимается проектированием страницы, а программист работает над вспомогательным объектом.

Представление по шаблону имеет два существенных недостатка. Во-первых, реализуя представление в виде страницы сервера, последнюю весьма легко переполнить логикой. Это значительно усложнит ее дальнейшую поддержку, особенно для людей, не являющихся программистами. Необходимо тщательно следить за тем, чтобы страница оставалась простой и ориентированной только на отображение, а вся программная логика была реализована во вспомогательном объекте. Во-вторых, представление по шаблону сложнее тестировать, чем представление с преобразованием. Большинство реализаций представления по шаблону ориентированы на использование в рамках Web-сервера, в результате чего их невозможно или практически невозможно протестировать в другом контексте. Реализации представления с преобразованием значительно легче поддаются тестированию и могут функционировать и при отсутствии запущенного Web-сервера.

Обсуждая варианты представления, нельзя не вспомнить о двухэтапном представлении (Two Step View). В зависимости от используемой схемы шаблона, это типовое решение можно реализовать и с применением специальных дескрипторов. Тем не менее реализация двухэтапного представления на основе представления с преобразованием может оказаться значительно легче.

3.5.5 Паттерн Transform View

Представление с преобразованием (Transform View) Представление, которое поочередно обрабатывает элементы данных домена и преобразует их в код HTML.

Выполняя запросы к слоям домена и источника данных, вы получаете от них нужные данные, однако без форматирования, необходимого для создания Web-страницы. Визуализацией полученных данных в элементы Web-страницы занимается объект, выполняющий роль представления в шаблоне MVC. В типовом решении представление с преобразованием процесс визуализации данных рассматривается как преобразование, на вход которого подаются данные из модели, а на выходе принимается код HTML.

Принцип действия

В основе типового решения представление с преобразованием лежит идея написания программы, которая бы просматривала данные домена и преобразовывала их в код

HTML. В процессе выполнения такая программа последовательно проходит по структуре данных домена и, обнаруживая новый фрагмент данных, создает их описание в терминах HTML

Основное отличие представления с преобразованием от представления по шаблону заключается в способе организации представления. Представление по шаблону организовано с учетом размещения на экране выходных данных. Представление с преобразованием ориентировано на использование отдельных преобразований для каждого вида входных данных. Преобразованиями управляет нечто наподобие простого цикла, который поочередно просматривает каждый входной элемент, подбирает для него подходящее преобразование и применяет это преобразование. Таким образом, правила представления с преобразованием могут быть организованы в любом порядке - на результат это не повлияет.

Представление с преобразованием может быть написано на любом языке. Тем не менеена данный момент наиболее популярным языком для написания представлений с преобразованием является XSLT.

Для применения преобразований XSLT данные домена должны находиться в формате XML Этого проще достичь, когда логика домена сразу же возвращает данные в формате XML или любом другом, который может быть легко преобразован в XML, например объекты .NET. В противном случае придется самостоятельно генерировать код XML

Код XML, поступающий на вход преобразования, не обязательно должен быть строкой (если только этого не требует канал передачи данных). Как правило, гораздо быстрее и легче организовать входные данные в модель DOM.

Данные домена в формате XML передаются процессору XSLT. В последнее время на рынке программного обеспечения доступно все больше и больше коммерческих процессоров XSLT. Логика преобразования содержится в таблице стилей XSLT, которая также передается процессору. Последний применяет таблицу стилей к входным данным XML и преобразует их в код HTML, который сразу же может быть помещен в HTTP-запрос.

Purpose

Выбор между представлением с преобразованием и представлением по шаблону зависит от того, какую среду разработки предпочитает команда, занимающаяся проектированием представлений. Ключевым фактором здесь является наличие необходимых средств. Для написания представлений по шаблону можно использовать практически любой HTML-редактор, в то время как средства для работы с XSLT не так распространены, да и возможностей у них значительно меньше. Кроме того, язык XSLT представляет собой достаточно сложную смесь функционального программирования и синтаксиса XML, а потому овладеть им сможет далеко не каждый.

3.5.6 Паттерн Two Step View

Двухэтапное представление (Two Step View). Выполняет визуализацию данных домена в два этапа: вначале формирует некое подобие логической страницы, после чего преобразует логическую странииу в формат HTML.

Если разрабатываемое Web-приложение содержит много страниц, вам, скорее всего, захочется оформить и организовать их в одном стиле. Действительно, сайт, каждая страница которого имеет совершенно другой вид, способен окончательно запутать посетителей. Кроме того, вам может понадобиться быстрый способ глобального изменения внешнего вида приложения. К сожалению, использование представления по шаблону или представления с преобразованием значительно затруднит этот процесс. Данные типовые решения не исключают дублирования фрагментов представлений в нескольких страницах или компонентах преобразований, в результате чего глобальное изменение внешнего вида может потребовать внесения изменений в несколько различных файлов.

Избежать подобных проблем помогает двухэтапное представление, выполняющее преобразование данных в два этапа. Вначале данные модели преобразуются в логическое представление, не содержащее какого-либо специального форматирования. Затем полученное логическое представление путем применения необходимого форматирования трансформируется в HTML. В этом случае глобальные изменения внешнего вида Web-сайта приходится проводить только в одном месте, а именно на втором этапе преобразования. Кроме того, подобная схема позволяет отображать одни и те же данные несколькими способами, что также определяется на втором этапе.

Принцип действия

Главной особенностью этого типового решения является выполнение преобразования данных в формат HTML в два этапа. На первом этапе информация, полученная от модели, организуется в некую логическую структуру, которая описывает визуальные элементы будущего отображения, однако еще не содержит кода HTML. На втором этапе полученная структура преобразуется в код HTML.

Упомянутая промежуточная структура представляет собой некоторое подобие логического "экрана". Ее элементами могут быть поля ввода, верхние и нижние колонтитулы, таблицы, переключатели и т.п. В связи с этим данную структуру можно по праву назвать моделью представления. Очевидно также, что она вынуждает будущие страницы сайта следовать одному стилю. Для большей наглядности модель представления можно представить себе как систему, которая определяет элементы управления страницы и содержащиеся в них данные, однако не описывает их внешний вид в терминах HTML.

Для построения каждого логического окна применяется собственный код. Методы первого этапа обращаются к модели данных домена, будь то база данных, модель предметной области (Domain Model) или объект переноса данных (Data Transfer Object), извлекают из нее информацию, необходимую для построения экрана, и помещают эту информацию в логическое представление.

На втором этапе полученная логическая структура преобразуется в код HTML. Методы второго этапа "знают", какие элементы есть в логической структуре и как визуализировать каждый из этих элементов. Таким образом, система с множеством экранов может быть трансформирована в код HTML путем единственного прохождения второго этапа, благодаря чему решение о варианте преобразования в HTMLпринимается в одном месте. Разумеется, воспользоваться таким преимуществом удастся только в том случае, когда логические экраны компонуются по одному принципу.

Существует несколько способов построени двухэтапного представления. Наиболее простой из них — двухэтапное применение XSLT. Одноэтапное применение технологии XSLT следует подходу, реализованному в представлении с преобразованием, при котором каждой странице соответствует своя таблица стилей XSLT, преобразующая данные домена в формате XML в код HTML. В двухэтапном варианте этого подхода применяются две таблицы стилей XSLT: первая преобразует данные домена в формате XML в логическое представление в формате XML, а вторая преобразует логическое представление в формате ХМL в код HTML

Возможной альтернативой этому подходу является использование классов. В этом случае логическое представление определяется как набор классов: класс таблицы, класс строки и т.п. (рис. 3.25). Методы первого этапа извлекают данные домена и создают экземпляры описанных классов, помещая данные в структуру, моделирующую логический экран. На втором этапе для полученных экземпляров классов генерируется код HTML Это делают либо сами классы, либо специальный класс, предназначенный для выполнения визуализации. И первый и второй подход основан на применении представления с преобразованием.

Вместо этого двухэтапное представление может быть построено на основе представления по шаблону. В этом случае шаблон страницы составляется с учетом структуры логического экрана, например:

3.5 Data presentation patterns in WEB

Рисунок 3.25 Пример двухэтапного преобразования с ипользованием классов

После этого система шаблонов преобразует "логические" дескрипторы, подобные показанному выше, в формат HTML При такой схеме определение страницы не содержит кода HTML, а только дескрипторы логического экрана, вследствие чего полученная страница будет представлять собой документ XML и не сможет быть отредактирована с помощью HTML-редакторов типа WYSIWYG.

Purpose

Главным преимуществом двухэтапного представления является возможность разбить преобразование данных на два этапа, что облегчает проведение глобальных изменений. Подобная схема преобразования может оказаться чрезвычайно полезной в двух ситуациях: Web-приложения с несколькими вариантами внешнего вида и Web-приложения с одним варианто внешнего вида. Что касается Web-приложений с несколькими вариантами внешнего вида, они еще не так распространены, однако все больше и больше входят в употребление. В таких приложениях одна и та же базовая функциональность используется разными компаниями и сайт каждой компании имеет собственное оформление. Хорошим примером подобных приложений являются системы бронирования билетов различных авиакомпаний. Каждая из этих систем имеет свой внешний вид, однако, приглядевшись к структуре их страниц, легко заметить, что в их основе лежит одно и то же базовое решение


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Object oriented programming

Terms: Object oriented programming