<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
<sect3 id="zend.controller.actionhelpers.contextswitch">
    <title>ContextSwitch and AjaxContext</title>

    <para>
        The <emphasis>ContextSwitch</emphasis> action helper is intended for
        facilitating returning different response formats on request.
        The <emphasis>AjaxContext</emphasis> helper is a specialized version of
        <emphasis>ContextSwitch</emphasis> that facilitates returning responses
        to XmlHttpRequests.
    </para>

    <para>
        To enable either one, you must provide hinting in your controller as to
        what actions can respond to which contexts. If an incoming request
        indicates a valid context for the given action, the helper will then:
    </para>

    <itemizedlist>
        <listitem><para>
                Disable layouts, if enabled.
        </para></listitem>

        <listitem><para>
                Set an alternate view suffix, effectively requiring a separate
                view script for the context.
        </para></listitem>

        <listitem><para>
                Send appropriate response headers for the context desired.
        </para></listitem>

        <listitem><para>
                Optionally, call specified callbacks to setup the context and/or
                perform post-processing.
        </para></listitem>
    </itemizedlist>

    <para>
        As an example, let's consider the following controller:
    </para>

    <programlisting language="php"><![CDATA[
class NewsController extends Zend_Controller_Action
{
    /**
     * Landing page; forwards to listAction()
     */
    public function indexAction()
    {
        $this->_forward('list');
    }

    /**
     * List news items
     */
    public function listAction()
    {
    }

    /**
     * View a news item
     */
    public function viewAction()
    {
    }
}
]]></programlisting>

    <para>
        Let's say that we want the <methodname>listAction()</methodname> to also be
        available in an <acronym>XML</acronym> format. Instead of creating a different action, we
        can hint that it can return an <acronym>XML</acronym> response:
    </para>

    <programlisting language="php"><![CDATA[
class NewsController extends Zend_Controller_Action
{
    public function init()
    {
        $contextSwitch = $this->_helper->getHelper('contextSwitch');
        $contextSwitch->addActionContext('list', 'xml')
                      ->initContext();
    }

    // ...
}
]]></programlisting>

    <para>
        What this will do is:
    </para>

    <itemizedlist>
        <listitem><para>
                Set the 'Content-Type' response header to '<filename>text/xml</filename>'.
        </para></listitem>

        <listitem><para>
                Change the view suffix to '<filename>xml.phtml</filename>' (or, if you use an
                alternate view suffix, 'xml.[your suffix]').
        </para></listitem>
    </itemizedlist>

    <para>
        Now, you'll need to create a new view script, '<filename>news/list.xml.phtml</filename>',
        which will create and render the <acronym>XML</acronym>.
    </para>

    <para>
        To determine if a request should initiate a context switch, the helper
        checks for a token in the request object. By default, it looks for the
        'format' parameter, though this may be configured. This means that, in
        most cases, to trigger a context switch, you can add a 'format'
        parameter to your request:
    </para>

    <itemizedlist>
        <listitem><para>
                Via <acronym>URL</acronym> parameter: <filename>/news/list/format/xml</filename>
                (recall, the default routing schema allows for arbitrary key to value pairs
                following the action)
        </para></listitem>

        <listitem><para>
                Via <acronym>GET</acronym> parameter: <command>/news/list?format=xml</command>
        </para></listitem>
    </itemizedlist>

    <para>
        <emphasis>ContextSwitch</emphasis> allows you to specify arbitrary contexts,
        including what suffix change will occur (if any), any response headers
        that should be sent, and arbitrary callbacks for initialization and post
        processing.
    </para>

    <sect4 id="zend.controller.actionhelpers.contextswitch.contexts">
        <title>Default Contexts Available</title>

        <para>
            By default, two contexts are available to the
            <emphasis>ContextSwitch</emphasis> helper: json and xml.
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <emphasis><acronym>JSON</acronym></emphasis>. The <acronym>JSON</acronym>
                    context sets the 'Content-Type' response header to
                    '<filename>application/json</filename>', and the view script suffix to
                    '<filename>json.phtml</filename>'.
                </para>

                <para>
                    By default, however, no view script is required. It will
                    simply serialize all view variables, and emit the <acronym>JSON</acronym>
                    response immediately.
                </para>

                <para>
                    This behaviour can be disabled by turning off the automatic
                    <acronym>JSON</acronym> serialization:
                </para>

                <programlisting language="php"><![CDATA[
$this->_helper->contextSwitch()->setAutoJsonSerialization(false);
]]></programlisting>
            </listitem>

            <listitem>
                <para>
                    <emphasis><acronym>XML</acronym></emphasis>. The <acronym>XML</acronym> context
                    sets the 'Content-Type' response header to '<filename>text/xml</filename>', and
                    the view script suffix to '<filename>xml.phtml</filename>'. You will need to
                    create a new view script for the context.
                </para>
            </listitem>
        </itemizedlist>
    </sect4>

    <sect4 id="zend.controller.actionhelpers.contextswitch.custom">
        <title>Creating Custom Contexts</title>

        <para>
            Sometimes, the default contexts are not enough. For instance, you may wish to return
            <acronym>YAML</acronym>, or serialized <acronym>PHP</acronym>, an
            <acronym>RSS</acronym> or <acronym>ATOM</acronym> feed, etc.
            <emphasis>ContextSwitch</emphasis> allows you to do so.
        </para>

        <para>
            The easiest way to add a new context is via the
            <methodname>addContext()</methodname> method. This method takes two arguments,
            the name of the context, and an array specification. The
            specification should include one or more of the following:
        </para>

        <itemizedlist>
            <listitem>
                <para><emphasis>suffix</emphasis>: the suffix to prepend to the
                default view suffix as registered in the ViewRenderer.</para>
            </listitem>

            <listitem>
                <para><emphasis>headers</emphasis>: an array of header to value
                    pairs you wish sent as part of the response.</para>
            </listitem>

            <listitem>
                <para><emphasis>callbacks</emphasis>: an array containing one or
                more of the keys 'init' or 'post', pointing to valid <acronym>PHP</acronym>
                callbacks that can be used for context initialization and post
                processing.</para>

                <para>Initialization callbacks occur when the context is
                detected by <emphasis>ContextSwitch</emphasis>. You can use it to
                perform arbitrary logic that should occur. As an example,
                the <acronym>JSON</acronym> context uses a callback to disable the ViewRenderer
                when the automatic <acronym>JSON</acronym> serialization is on.</para>

                <para>Post processing occurs during the action's
                <methodname>postDispatch()</methodname> routine, and can be used to perform
                arbitrary logic. As an example, the <acronym>JSON</acronym> context uses a callback
                to determine if the automatic <acronym>JSON</acronym> serialization is on; if so,
                it serializes the view variables to <acronym>JSON</acronym> and sends the response,
                but if not, it re-enables the ViewRenderer.</para>
            </listitem>
        </itemizedlist>

        <para>
            There are a variety of methods for interacting with contexts:
        </para>

        <itemizedlist>
            <listitem><para>
                <methodname>addContext($context, array $spec)</methodname>: add a new
                context. Throws an exception if the context already exists.
            </para></listitem>

            <listitem><para>
                <methodname>setContext($context, array $spec)</methodname>: add a new
                context or overwrite an existing context. Uses the same
                specification as <methodname>addContext()</methodname>.
            </para></listitem>

            <listitem><para>
                <methodname>addContexts(array $contexts)</methodname>: add many contexts at
                once. The <varname>$contexts</varname> array should be an array of
                context to specification pairs. If any of the contexts already
                exists, it will throw an exception.
            </para></listitem>

            <listitem><para>
                <methodname>setContexts(array $contexts)</methodname>: add new contexts and
                overwrite existing ones. Uses the same specification as
                <methodname>addContexts()</methodname>.
            </para></listitem>

            <listitem><para>
                <methodname>hasContext($context)</methodname>: returns true if the context
                exists, false otherwise.
            </para></listitem>

            <listitem><para> <methodname>getContext($context)</methodname>: retrieve a
                    single context by name. Returns an array following the
                    specification used in <methodname>addContext()</methodname>.
            </para></listitem>

            <listitem><para>
                <methodname>getContexts()</methodname>: retrieve all contexts. Returns an
                array of context to specification pairs.
            </para></listitem>

            <listitem><para>
                <methodname>removeContext($context)</methodname>: remove a single context by
                name. Returns true if successful, false if the context was not
                found.
            </para></listitem>

            <listitem><para>
                <methodname>clearContexts()</methodname>: remove all contexts.
            </para></listitem>
        </itemizedlist>
    </sect4>

    <sect4 id="zend.controller.actionhelpers.contextswitch.actions">
        <title>Setting Contexts Per Action</title>

        <para>
            There are two mechanisms for setting available contexts. You can
            either manually create arrays in your controller, or use several
            methods in <emphasis>ContextSwitch</emphasis> to assemble them.
        </para>

        <para>
            The principle method for adding action to context relations is
            <methodname>addActionContext()</methodname>. It expects two arguments, the
            action to which the context is being added, and either the name of a
            context or an array of contexts. As an example, consider the
            following controller class:
        </para>

        <programlisting language="php"><![CDATA[
class FooController extends Zend_Controller_Action
{
    public function listAction()
    {
    }

    public function viewAction()
    {
    }

    public function commentsAction()
    {
    }

    public function updateAction()
    {
    }
}
]]></programlisting>

        <para>
            Let's say we wanted to add an <acronym>XML</acronym> context to the 'list' action, and
            <acronym>XML</acronym> and <acronym>JSON</acronym> contexts to the 'comments' action.
            We could do so in the <methodname>init()</methodname> method:
        </para>

        <programlisting language="php"><![CDATA[
class FooController extends Zend_Controller_Action
{
    public function init()
    {
        $this->_helper->contextSwitch()
             ->addActionContext('list', 'xml')
             ->addActionContext('comments', array('xml', 'json'))
             ->initContext();
    }
}
]]></programlisting>

        <para>
            Alternately, you could simply define the array property
            <varname>$contexts</varname>:
        </para>

        <programlisting language="php"><![CDATA[
class FooController extends Zend_Controller_Action
{
    public $contexts = array(
        'list'     => array('xml'),
        'comments' => array('xml', 'json')
    );

    public function init()
    {
        $this->_helper->contextSwitch()->initContext();
    }
}
]]></programlisting>

        <para>
            The above is less overhead, but also prone to potential errors.
        </para>

        <para>
            The following methods can be used to build the context mappings:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <methodname>addActionContext($action, $context)</methodname>: marks one
                    or more contexts as available to an action. If mappings
                    already exists, simply appends to those mappings.
                    <varname>$context</varname> may be a single context, or an array
                    of contexts.
                </para>

                <para>
                    A value of <constant>TRUE</constant> for the context will mark
                    all available contexts as available for the action.
                </para>

                <para>
                    An empty value for <varname>$context</varname> will disable all contexts for
                    the given action.
                </para>
            </listitem>

            <listitem><para>
                    <methodname>setActionContext($action, $context)</methodname>: marks one
                    or more contexts as available to an action. If mappings
                    already exists, it replaces them with those specified.
                    <varname>$context</varname> may be a single context, or an array
                    of contexts.
            </para></listitem>

            <listitem><para>
                    <methodname>addActionContexts(array $contexts)</methodname>: add several
                    action to context pairings at once. <varname>$contexts</varname>
                    should be an associative array of action to context pairs. It
                    proxies to <methodname>addActionContext()</methodname>, meaning that if
                    pairings already exist, it appends to them.
            </para></listitem>

            <listitem><para>
                    <methodname>setActionContexts(array $contexts)</methodname>: acts like
                    <methodname>addActionContexts()</methodname>, but overwrites existing
                    action to context pairs.
            </para></listitem>

            <listitem><para>
                    <methodname>hasActionContext($action, $context)</methodname>: determine
                    if a particular action has a given context.
            </para></listitem>

            <listitem><para>
                    <methodname>getActionContexts($action = null)</methodname>: returns
                    either all contexts for a given action, or all
                    action to context pairs.
            </para></listitem>

            <listitem><para>
                    <methodname>removeActionContext($action, $context)</methodname>: remove
                    one or more contexts from a given action.
                    <varname>$context</varname> may be a single context or an array of
                    contexts.
            </para></listitem>

            <listitem><para>
                    <methodname>clearActionContexts($action = null)</methodname>: remove all
                    contexts from a given action, or from all actions with
                    contexts.
            </para></listitem>
        </itemizedlist>
    </sect4>

    <sect4 id="zend.controller.actionhelpers.contextswitch.initcontext">
        <title>Initializing Context Switching</title>

        <para>
            To initialize context switching, you need to call
            <methodname>initContext()</methodname> in your action controller:
        </para>

        <programlisting language="php"><![CDATA[
class NewsController extends Zend_Controller_Action
{
    public function init()
    {
        $this->_helper->contextSwitch()->initContext();
    }
}
]]></programlisting>

        <para>
            In some cases, you may want to force the context used; for instance,
            you may only want to allow the <acronym>XML</acronym> context if context switching is
            activated. You can do so by passing the context to
            <methodname>initContext()</methodname>:
        </para>

        <programlisting language="php"><![CDATA[
$contextSwitch->initContext('xml');
]]></programlisting>
    </sect4>

    <sect4 id="zend.controller.actionhelpers.contextswitch.misc">
        <title>Additional Functionality</title>

        <para>
            A variety of methods can be used to alter the behaviour of the
            <emphasis>ContextSwitch</emphasis> helper. These include:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <methodname>setAutoJsonSerialization($flag)</methodname>: By default,
                    <acronym>JSON</acronym> contexts will serialize any view variables to
                    <acronym>JSON</acronym> notation and return this as a response. If you wish to
                    create your own response, you should turn this off; this
                    needs to be done prior to the call to
                    <methodname>initContext()</methodname>.
                </para>

                <programlisting language="php"><![CDATA[
$contextSwitch->setAutoJsonSerialization(false);
$contextSwitch->initContext();
]]></programlisting>

                <para>
                    You can retrieve the value of the flag with
                    <methodname>getAutoJsonSerialization()</methodname>.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>setSuffix($context, $suffix,
                        $prependViewRendererSuffix)</methodname>: With this method,
                    you can specify a different suffix to use for a given
                    context. The third argument is used to indicate whether or
                    not to prepend the current ViewRenderer suffix with the new
                    suffix; this flag is enabled by default.
                </para>

                <para>
                    Passing an empty value to the suffix will cause only the
                    ViewRenderer suffix to be used.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>addHeader($context, $header, $content)</methodname>: Add a
                    response header for a given context. <varname>$header</varname> is
                    the header name, and <varname>$content</varname> is the value to
                    pass for that header.
                </para>

                <para>
                    Each context can have multiple headers;
                    <methodname>addHeader()</methodname> adds additional headers to the
                    context's header stack.
                </para>

                <para>
                    If the <varname>$header</varname> specified already exists for the
                    context, an exception will be thrown.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>setHeader($context, $header, $content)</methodname>:
                    <methodname>setHeader()</methodname> acts just like
                    <methodname>addHeader()</methodname>, except it allows you to overwrite
                    existing context headers.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>addHeaders($context, array $headers)</methodname>: Add
                    multiple headers at once to a given context. Proxies to
                    <methodname>addHeader()</methodname>, so if the header already exists,
                    an exception will be thrown. <varname>$headers</varname> is an
                    array of header to context pairs.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>setHeaders($context, array $headers.)</methodname>: like
                    <methodname>addHeaders()</methodname>, except it proxies to
                    <methodname>setHeader()</methodname>, allowing you to overwrite existing
                    headers.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getHeader($context, $header)</methodname>: retrieve the
                    value of a header for a given context. Returns null if not
                    found.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>removeHeader($context, $header)</methodname>: remove a
                    single header for a given context.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>clearHeaders($context, $header)</methodname>: remove all
                    headers for a given context.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>setCallback($context, $trigger, $callback)</methodname>: set
                    a callback at a given trigger for a given context. Triggers
                    may be either 'init' or 'post' (indicating callback will be
                    called at either context initialization or postDispatch).
                    <varname>$callback</varname> should be a valid <acronym>PHP</acronym> callback.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>setCallbacks($context, array $callbacks)</methodname>: set
                    multiple callbacks for a given context. <varname>$callbacks</varname>
                    should be trigger to callback pairs. In actuality, the most callbacks
                    that can be registered are two, one for initialization and
                    one for post processing.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getCallback($context, $trigger)</methodname>: retrieve a
                    callback for a given trigger in a given context.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getCallbacks($context)</methodname>: retrieve all callbacks
                    for a given context. Returns an array of trigger to callback
                    pairs.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>removeCallback($context, $trigger)</methodname>: remove a
                    callback for a given trigger and context.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>clearCallbacks($context)</methodname>: remove all
                    callbacks for a given context.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>setContextParam($name)</methodname>: set the request
                    parameter to check when determining if a context switch has
                    been requested. The value defaults to 'format', but this
                    accessor can be used to set an alternate value.
                </para>

                <para>
                    <methodname>getContextParam()</methodname> can be used to retrieve the
                    current value.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>setAutoDisableLayout($flag)</methodname>: By default,
                    layouts are disabled when a context switch occurs; this is
                    because typically layouts will only be used for returning
                    normal responses, and have no meaning in alternate contexts.
                    However, if you wish to use layouts (perhaps you may have a
                    layout for the new context), you can change this behaviour
                    by passing a false value to
                    <methodname>setAutoDisableLayout()</methodname>. You should do this
                    <emphasis>before</emphasis> calling
                    <methodname>initContext()</methodname>.
                </para>

                <para>
                    To get the value of this flag, use the accessor
                    <methodname>getAutoDisableLayout()</methodname>.
                </para>
            </listitem>

            <listitem>
                <para>
                    <methodname>getCurrentContext()</methodname> can be used to determine
                    what context was detected, if any. This returns null if no
                    context switch occurred, or if called before
                    <methodname>initContext()</methodname> has been invoked.
                </para>
            </listitem>
        </itemizedlist>
    </sect4>

    <sect4 id="zend.controller.actionhelpers.contextswitch.ajaxcontext">
        <title>AjaxContext Functionality</title>

        <para>
            The <emphasis>AjaxContext</emphasis> helper extends
            <emphasis>ContextSwitch</emphasis>, so all of the functionality listed for
            <emphasis>ContextSwitch</emphasis> is available to it. There are a few key
            differences, however.
        </para>

        <para>
            First, it uses a different action controller property for
            determining contexts, <varname>$ajaxable</varname>. This is so you can
            have different contexts used for <acronym>AJAX</acronym> versus normal
            <acronym>HTTP</acronym> requests. The various
            *<methodname>ActionContext()</methodname>* methods of
            <emphasis>AjaxContext</emphasis> will write to this property.
        </para>

        <para>
            Second, it will only trigger if an XmlHttpRequest has occurred, as
            determined by the request object's <methodname>isXmlHttpRequest()</methodname>
            method. Thus, if the context parameter ('format') is passed in the
            request, but the request was not made as an XmlHttpRequest, no
            context switch will trigger.
        </para>

        <para>
            Third, <emphasis>AjaxContext</emphasis> adds an additional context,
            <acronym>HTML</acronym>. In this context, it sets the suffix to
            '<filename>ajax.phtml</filename>' in order to differentiate the context from a normal
            request. No additional headers are returned.
        </para>

        <example id="zend.controller.actionhelpers.contextswitch.ajaxcontext.example">
            <title>Allowing Actions to Respond To Ajax Requests</title>

            <para>
                In this following example, we're allowing requests to the
                actions 'view', 'form', and 'process' to respond to <acronym>AJAX</acronym>
                requests. In the first two cases, 'view' and 'form', we'll
                return <acronym>HTML</acronym> snippets with which to update the page; in the
                latter, we'll return <acronym>JSON</acronym>.
            </para>

            <programlisting language="php"><![CDATA[
class CommentController extends Zend_Controller_Action
{
    public function init()
    {
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('view', 'html')
                    ->addActionContext('form', 'html')
                    ->addActionContext('process', 'json')
                    ->initContext();
    }

    public function viewAction()
    {
        // Pull a single comment to view.
        // When AjaxContext detected, uses the comment/view.ajax.phtml
        // view script.
    }

    public function formAction()
    {
        // Render the "add new comment" form.
        // When AjaxContext detected, uses the comment/form.ajax.phtml
        // view script.
    }

    public function processAction()
    {
        // Process a new comment
        // Return the results as JSON; simply assign the results as
        // view variables, and JSON will be returned.
    }
}
]]></programlisting>

            <para>
                On the client end, your <acronym>AJAX</acronym> library will simply request the
                endpoints '<filename>/comment/view</filename>',
                '<filename>/comment/form</filename>', and
                '<filename>/comment/process</filename>', and pass the 'format' parameter:
                '<filename>/comment/view/format/html</filename>',
                '<filename>/comment/form/format/html</filename>',
                '<filename>/comment/process/format/json</filename>'. (Or you can pass the parameter
                via query string: e.g., "?format=json".)
            </para>

            <para>
                Assuming your library passes the 'X-Requested-With:
                XmlHttpRequest' header, these actions will then return the
                appropriate response format.
            </para>
        </example>
    </sect4>
</sect3>
<!--
vim:se ts=4 sw=4 et:
-->
