Tài liệu Embedding Perl in HTML with Mason Chapter 4: APIs- P1 pptx

23 388 0
Tài liệu Embedding Perl in HTML with Mason Chapter 4: APIs- P1 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 4: APIs- P1 Mason is more than just a templating system. It provides a framework for translating requests into output. 1 This framework has a number of class/object APIs worth knowing about. You certainly won't need to use most of these methods very often, but you will probably want to use at least some of them in many of your Mason-based projects. This chapter documents those APIs. For a more concise reference to these methods, see Appendix B . Request Class and Object API The request object in Mason represents the context of the current request process. For example, it knows where in the component wrapping chain it is, what arguments have been passed to various component calls, if you've been bad or good, and so on. It also allows you to change that context in various ways, such as by calling another component or aborting the request. The request API provides access to some of the most frequently used Mason features, particularly those relating to component calls, autohandlers, and aborting in the middle of a request. Recall, as first mentioned in Chapter 2 , that the Mason request object is available in all components as $m. The request class has only two class methods. The first, HTML::Mason::Request->new() , is intended for use by other Mason objects and is not documented for external use. If you want to make a new request object, use the make_subrequest() method provided by the request object, which is covered as part of the discussion of Mason's subrequest mechanism in Chapter 5 . The second class method, HTML::Mason::Request->instance() , returns the current Mason request object. This is useful if you have code outside of a Mason component that needs to access the request object. Inside components, you can just use $m. The request object's methods can be grouped together into several functional areas. Constructor Parameters A number of parameters can be set when creating a new request object. You will most often set these by passing them to the ApacheHandler's constructor or by setting them in your httpd.conf file. You may occasionally want to set one of these parameters on the fly for the current request. Finally, you will create a new request object when you want to make a subrequest, and you may want to set these parameters then. All of the following parameters are also available as get/set methods of the same name: • autoflush This attribute is discussed in "Buffer-Related Methods" , later in this chapter. • data_cache_defaults This returns a hash reference containing default options for the Request object's cache() method. • dhandler_name This is the name used for dhandlers. This defaults to "dhandler." • error_format This may be brief , text , line , or html . These produce an error message with no trace, a multiline error with trace information, a single-line error with tab-separated fields (suitable for writing to a log), and a fancy HTML format. Each of these methods corresponds to a method in the HTML::Mason::Exception class, such as as_text() or as_line(). You can create your own method in the HTML::Mason::Exception namespace, such as as_you_wish(), in which case you could set this parameter to "you_wish." This method will receive a single argument, the exception object, and is expected to return a string containing the formatted error message. In a mod_perl or CGI environment, this defaults to html format. Otherwise, the default is text . • error_mode This may be either fatal or output . In fatal mode, errors are thrown as exceptions. In output mode, the exception is converted to a text representation and sent to the same output stream as normal content. In a mod_perl or CGI environment, the default is output , which means that errors go the client. In any other environment, the default is fatal . If you set this to fatal in a web environment, errors will end up in your web server's logs. If you wish to implement your own exception-handling mechanism around Mason, set this to fatal and catch the exceptions yourself. • max_recurse This can be used to set the maximum stack size for component calls and subrequests. It defaults to 32, which is likely to be more than enough for any application. But if for some reason you need more, you can set this to a higher number. • out_method This parameter indicates where output should be sent and must be a reference to either a scalar or a subroutine. If it is a scalar reference, output will be appended to this scalar. If it is a subroutine reference (often called a code reference in Perl parlance), this subroutine will be called with a list of arguments whenever output needs to be sent, which occurs after the output has passed through all of Mason's buffers. The default out_method will print its arguments to STDOUT. In a mod_perl or CGI environment, this means that output gets sent to the client. Calling Other Components Besides the component call tag (<& &>) discussed in Chapter 2 , there are several other ways for one component to call another: • comp(component, arguments) This method is exactly like the <& .&> tag discussed in Chapter 2. It allows you to call another component, specified either by path or by supplying a component object as the first argument. Arguments are passed exactly as with the component call tag. The return value of this method is the return value of the component being called. Most components will not have an explicit return value and will return undef. Any output generated by the called component becomes part of the output of that particular request. As of Mason 1.10, a hash reference can be provided as an additional first argument to this method. The contents of this hash reference are used to modify the way the component call is processed. Right now, only one parameter -- store -- is accepted for this hash reference. The value of the store key should be a reference to a scalar, into which Mason will place the output for the component. For example: $m->comp( { store => \$content }, 'Hello.comp', to => 'World' ); The output of Hello.comp would be available in the $content variable. This functionality is fundamentally the same as that provided by the scomp() method except that it allows you to capture the component's return value in addition to its output. • scomp(component, arguments) This is exactly like the comp() method except that the called component's output is returned as a string instead of being sent to the output stream. This is analogous to the use of sprintf() instead of printf() in C. Components called via this method go through all of the normal steps of component execution. If you have a component that generates output and has a return value and you want to capture that output in a scalar, you should use the store component call modifier. • content This method is relevant only inside a component called with content, a feature we saw briefly in Chapter 2 but will cover more completely in Chapter 5 . This method returns the block of content wrapped by the component call. This will make more sense once you've read "Calling Components with Content Blocks" in Chapter 5. Aborting the Flow of Execution Mason provides a way to abort the flow of execution during a request. Several request object methods relate to doing so and examining what happened afterward. • abort(optional argument) Calling this method will immediately abort the execution of the current request. If an argument is given to this method, this value will be available via the aborted_value() method after calling abort(). Since this method is implemented internally via Perl's die() function, it may be caught by an eval block (eval { .}). In this case, you may call the aborted() method to distinguish this exception from one generated by something else in your code. The value of $@ will be an exception object of the class HTML::Mason::Exception::Abort. In a web context, if you don't catch the abort call via an eval block, the return value will be used as the server status code. The following example takes advantage of that fact to deny access unless a user has authenticated himself to Apache: <%init> use Apache::Constants; $m->abort(FORBIDDEN) unless $r->connection- >user; </%init> • aborted This method returns a boolean value indicating whether or not abort() has been called previously during the current request. • aborted_value When aborted() is true, this method returns whatever value was passed to the abort() call. If you are using eval blocks for exception handling in your components, it is important to propagate exceptions generated from a call to abort(). Here is one way do this: eval { $m->call_next(%ARGS) }; if ($@) { if ($m->aborted) { # pass this up to a higher level die $@; } else { # something else that's bad happened $m->comp( 'exception_handler', exception => $@ ); } } The Wrapping Chain These are methods related to the wrapping chain, which was discussed in Chapter 3 . • call_next(arguments) When the currently executing component is part of a wrapping chain, this method will call the next component in the chain, passing it the current component's arguments and any arguments specified in the call to call_next(). If there is no next component to call, it will throw an exception. • fetch_next This method returns the next component object in the wrapping chain. This is the same component that would be run upon calling call_next(). This object may then be passed to a component call via the <& &> tag or the comp() method. • fetch_next_all This method returns an array of all of the components in the wrapping chain that have yet to be executed. They are returned in order based on their position in the wrapping chain. Dhandler-Related Methods Certain request object methods are specifically related to dhandlers: • decline This method was discussed in detail in Chapter 3 . Calling this method indicates that the current component does not wish to handle the request, in which case Mason will look for the next available dhandler to handle it. • dhandler_arg This method was also discussed in Chapter 3 . This method returns the remainder of the component path after stripping off the dhandler's directory. Given a call to /archives/2002/02/30/all and a dhandler component at /archives/dhandler , dhandler_arg() returns 2002/02/30/all . Miscellaneous Methods The request object also has some general-use methods: • file(filename) Given a file path, Mason will look for this file and return its contents as a string. If a relative path is given, Mason will prepend the path with the current component's directory if the component is file-based or the system's root directory otherwise. • comp_exists(component path) Given a component path, this method returns true if this path would successfully resolve to a component when passed to comp(). • print(output) This method takes a list of scalars, which will be sent as output. For example, the following two lines are identical: % $m->print($output); <% $output %> If you feel a need to call Perl's print() function from your Mason code, don't. Your code will be faster if you use $m->print() instead, though the result will be the same in the end. • interp This returns the Interp object associated with the current request. Chapter 6 documents this object's API. • count This method returns this request's number, which is unique for a given request and interpreter. Introspection The Mason request object provides numerous methods allowing introspection of the details of the current request. Some of these methods [...]... expense of increasing its complexity, thus making it less maintainable Caching can also be a big win in providing scalability when you have a bottleneck like an RDBMS For example, if your web site traffic quadruples in one day, caching the results of some database queries can be the difference between serving pages and watching your database box grind to a bloody, overloaded death Because caching is so... caching is so useful, Mason has a simple caching system that you can use from within your components Mason' s caching system is merely a thin wrapper over DeWitt Clinton's excellent Cache::Cache modules These modules provide a number of caching backends such as file or shared memory caches with a simple, feature-rich API All caches can be limited to a certain size using an LRU algorithm In addition, it is... Buffer-Related Methods The following methods all deal with Mason' s buffer objects A typical request starts off with a single base buffer For each component that is called in the component stack, another buffer will be added to the stack In addition, filtering and other special Mason features will add and remove additional buffers The buffer objects have their own API, detailed later in this chapter, but you will... component objects, while others return information about the arguments passed to components These methods are useful if you are using autohandlers (particularly more than one) and you want to get some information about the components in a request Using some of these methods requires an understanding of autohandlers and the wrapping chain, a topic that was covered in Chapter 3 • base_comp This method returns... contains, sending it to the next buffer below it in the stack Depending on what other buffers are below it, the flushing may continue through the entire stack, meaning output will be sent, or it may stop part of the way through because some buffers are set to ignore flushes If autoflush is on, this method is meaningless as no output is ever buffered Attempts to flush the buffers are ignored within the... to specify expiration times for stored data using a very flexible syntax For more information on Cache::Cache, simply install it from CPAN and type perldocCache::Cache on the command line Also check out http:/ /perl- cache.sourceforge.net/ for more information online • cache( ) This method returns the Cache::Cache object associated with this component, taking several options that allow you to control... method starts looking for an attribute in the component on which it is called, then ascends the inheritance hierarchy from there We want to start at the last component in the hierarchy the " child component" in order to give it a chance to override any attributes defined in its parents • request_args This method returns the arguments passed to the originally requested component In scalar context,... generated normally and then stored in the cache In the future, all calls to this component will use this cached output Of course, we may need to generate different output depending on what parameters are given as input In this case, we do something like this: $name return if $m->cache_self( key => $name ); # rest of init and output generation For every different value... the current component The first element of the array will be the current component and the last will be the first component in the stack If this method is called with an integer argument, then that number is used as an index number into the stack Just as with Perl arrays, negative integers start at the end of the stack and count backward my @comps = $m->callers # all components $m->callers(0) # current... implement a subclass of Mason' s default buffer class, HTML: :Mason: :Buffer The request API offers several methods for dealing with the buffer stack as a whole: • autoflush(boolean) This method can be used to turn autoflushing on and off When autoflushing is on, output is sent as soon as it is generated Otherwise, it is buffered until all components have run By default, autoflushing is off Remember that . brief , text , line , or html . These produce an error message with no trace, a multiline error with trace information, a single-line error with tab-separated. your code at the expense of increasing its complexity, thus making it less maintainable. Caching can also be a big win in providing scalability when you have

Ngày đăng: 14/12/2013, 12:15

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan