Examples:
embed:lithium\tests\cases\net\http\MediaTest::testMediaTypes(1-2)
embed:lithium\tests\cases\net\http\MediaTest::testMediaTypes(19-23)
embed:lithium\tests\cases\net\http\MediaTest::testMediaTypes(43-44)
Alternatively, can be used to detect the type name of a registered content type:
Media::type('application/json'); // returns 'json'
Media::type('application/javascript'); // returns 'javascript'
Media::type('text/javascript'); // also returns 'javascript'
Media::type('text/html'); // returns 'html'
Media::type('application/xhtml+xml'); // also returns 'html'
#### Content negotiation
When creating custom media types, specifying which content-type(s) to match isn't always
enough. For example, if you wish to serve a different set of templates to mobile web
browsers, you'd still want those templates served as HTML. You might add something like this:
Media::type('mobile', array('application/xhtml+xml', 'text/html'));
However, this would cause _all_ requests for HTML content to be interpreted as
'mobile'-type requests. Instead, we can use _content negotiation_ to granularly specify how
to match a particular type. Content negotiation is the process of examining the HTTP headers
provided in the request (including the content-types listed in the Accept header, and
optionally other things as well, like the Accept-Language or User-Agent headers), in
order to produce the best representation of the requested resource for the client; in other
words, the resource that most closely matches what the client is asking for.
Content negotiation with media types is made possible through the 'conditions' key of the
$options parameter, which contains an array of assertions made against the Request
object. Each assertion (array key) can be one of three different things:
- 'type' _boolean_: In the default routing, some routes have {:type} keys, which are
designed to match file extensions in URLs. These values act as overrides for the
HTTP Accept header, allowing different formats to be served with the same content
type. For example, if you're serving JSONP, you'll want to serve it with the same
content-type as JavaScript (since it is JavaScript), but you probably won't want to
use the same template(s) or other settings. Therefore, when serving JSONP content, you
can specify that the extension defined in the type must be present in the URL:
Media::type('jsonp', array('application/json'), array(
template settings...
'conditions' => array('type' => true)
));
Then, JSONP content will only ever be served when the request URL ends in .jsonp.
- ':' _string_: This type of assertion can be used to match against arbitrary
information in the request, including headers (i.e. 'http:user_agent'), environment
variables (i.e. 'env:home'), GET and POST data (i.e. 'query:foo' or 'data:foo',
respectively), and the HTTP method ('http:method') of the request. For more information
on possible keys, see lithium\action\Request::get().
- '' _boolean_: Uses detector checks added to the Request object to make
boolean assertions against the request. For example, if a detector called 'iPhone' is
attached, you can add 'iPhone' => true to the 'conditions' array in order to filter for
iPhone requests only. See lithium\action\Request::detect() for more information on adding
detectors.
public static type ( string $type, mixed $content = null, array $options = [] ) : mixed | ||
$type | string | A file-extension-style type name, i.e. `'txt'`, `'js'`, or `'atom'`. Alternatively, a mapped content type, i.e. `'text/html'`, `'application/atom+xml'`, etc.; in which case, the matching type name (i.e. '`html'` or `'atom'`) will be returned. |
$content | mixed | Optional. A string or array containing the content-type(s) that `$type` should map to. If `$type` is an array of content-types, the first one listed should be the "primary" type, and will be used as the `Content-type` header of any `Response` objects served through this type. |
$options | array | Optional. The handling options for this media type. Possible keys are: - `'view'` _string_: Specifies the view class to use when rendering this content. Note that no `'view'` class is specified by default. If you want to render templates using Lithium's default view class, use `'lithium\template\View'` - `'decode'` _mixed_: A (string) function name or (object) closure that handles decoding or unserializing content from this format. - `'encode'` _mixed_: A (string) function name or (object) closure that handles encoding or serializing content into this format. - `'cast'` _boolean_: Used with `'encode'`. If `true`, all data passed into the specified encode function is first cast to array structures. - `'paths'` _array_: Optional key/value pairs mapping paths for `'template'`, `'layout'`, and `'element'` template files. Any keys ommitted will use the default path. The values should be `String::insert()`-style paths or an array of `String::insert()`-style paths. If it is an array, each path will be tried in the order specified until a template is found. This is useful for allowing custom templates while falling back on default templates if no custom template was found. If you want to render templates without a layout, use a `false` value for `'layout'`. - `'conditions'` _array_: Optional key/value pairs used as assertions in content negotiation. See the above section on **Content Negotiation**. |
리턴 | mixed | If `$content` and `$options` are empty, returns an array with `'content'` and `'options'` keys, where `'content'` is the content-type(s) that correspond to `$type` (can be a string or array, if multiple content-types are available), and `'options'` is the array of options which define how this content-type should be handled. If `$content` or `$options` are non-empty, returns `null`. |
/** * This tests that setting custom paths and disabling layout * via `\lithium\net\http\Media::type()` is handled properly * by the default `\lithium\template\View` class and `File` * rendered adapter. */ public function testMediaTypeViewRender() { Media::type('view-integration-test', 'lithium/viewtest', array('view' => 'lithium\\template\\View', 'paths' => array('layout' => false, 'template' => array('{:library}/tests/mocks/template/view/adapters/{:template}.{:type}.php', '{:library}/tests/mocks/template/view/adapters/{:template}.html.php')))); // testing no layout with a custom type template $response = new Response(); $response->type('view-integration-test'); Media::render($response, array(), array('layout' => true, 'library' => 'lithium', 'template' => 'testTypeFile')); $this->assertEqual('This is a type test.', $response->body()); // testing the template falls back to the html template $response = new Response(); $response->type('view-integration-test'); Media::render($response, array(), array('layout' => true, 'library' => 'lithium', 'template' => 'testFile')); $this->assertEqual('This is a test.', $response->body()); // testing with a layout Media::type('view-integration-test', 'lithium/viewtest', array('view' => 'lithium\\template\\View', 'paths' => array('layout' => '{:library}/tests/mocks/template/view/adapters/testLayoutFile.html.php', 'template' => array('{:library}/tests/mocks/template/view/adapters/{:template}.{:type}.php', '{:library}/tests/mocks/template/view/adapters/{:template}.html.php')))); $response = new Response(); $response->type('view-integration-test'); Media::render($response, array(), array('layout' => true, 'library' => 'lithium', 'template' => 'testTypeFile')); $this->assertEqual("Layout top.\nThis is a type test.Layout bottom.", $response->body()); }
<?php use lithium\core\Libraries; use lithium\core\ConfigException; use lithium\template\View; use lithium\net\http\Media; use lithium\util\Set; // Define path to plugin and other constants defined('SMARTY_VERSION') or define('SMARTY_VERSION', '3.1.10'); // Allows us to test different versions without breaking things defined('LI3_SMARTY_PATH') or define('LI3_SMARTY_PATH', dirname(__DIR__)); defined('LI3_SMARTY_LIB') or define('LI3_SMARTY_LIB', dirname(__DIR__) . "/libraries/Smarty/" . SMARTY_VERSION . "/libs/"); Libraries::add('Smarty', array("path" => LI3_SMARTY_LIB, "bootstrap" => "Smarty.class.php")); $defaults = array('view' => '\\lithium\\template\\View', 'renderer' => '\\li3_smarty\\template\\view\\adapter\\Smarty', 'paths' => array('template' => array(LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.tpl', '{:library}/views/{:controller}/{:template}.{:type}.tpl'), 'element' => array(LITHIUM_APP_PATH . '/views/elements/{:template}.html.tpl', '{:library}/views/elements/{:template}.html.tpl'), 'layout' => false), 'compile_dir' => LITHIUM_APP_PATH . '/resources/templates_c', 'cache_dir' => LITHIUM_APP_PATH . '/resources/cache', 'template_dir' => array(LITHIUM_APP_PATH . "/views", LITHIUM_APP_PATH . "/views/pages"), 'plugin_dir' => array(LI3_SMARTY_PATH . "/plugins", LITHIUM_APP_PATH . "/extensions/plugins")); $keys = array_intersect_key($config, $defaults); foreach ($keys as $key => $val) { if (is_array($defaults[$key])) { $defaults[$key] = Set::merge($defaults[$key], $config[$key]); } else { $defaults[$key] = $val; } } /** * Map to the new renderer */ Media::type('default', null, $defaults);
use lithium\core\Libraries; use lithium\action\Dispatcher; use lithium\action\Response; use lithium\net\http\Media; use li3_less\core\Less; define('LI3_BOOTSTRAP_PATH', dirname(__DIR__)); /* * this filter allows automatic linking and loading of assets from `webroot` folder */ Dispatcher::applyFilter('_callable', function ($self, $params, $chain) { list($library, $asset) = explode('/', ltrim($params['request']->url, '/'), 2) + array("", ""); if ($asset && $library == 'li3_bootstrap' && ($path = Media::webroot($library)) && file_exists($file = "{$path}/{$asset}")) { return function () use($file) { $info = pathinfo($file); $media = Media::type($info['extension']); $content = (array) $media['content']; return new Response(array('headers' => array('Content-type' => reset($content)), 'body' => file_get_contents($file))); }; } return $chain->next($self, $params, $chain); }); /** * Here we check, if there is a library called `li3_less` * * If that is the case, we can directly work with the * less files, that is much more flexible. To get this * up and running, you need to add li3_less as a library * and load it _before_ the li3_bootstrap library like this: * * Libraries::add('li3_less');
* return $posts->to('json'); * }}} */ use lithium\util\Collection; Collection::formats('lithium\\net\\http\\Media'); /** * This filter is a convenience method which allows you to automatically route requests for static * assets stored within active plugins. For example, given a JavaScript file `bar.js` inside the * `li3_foo` plugin installed in an application, requests to `http://app/path/li3_foo/js/bar.js` * will be routed to `/path/to/app/libraries/plugins/li3_foo/webroot/js/bar.js` on the filesystem. * In production, it is recommended that you disable this filter in favor of symlinking each * plugin's `webroot` directory into your main application's `webroot` directory, or adding routing * rules in your web server's configuration. */ use lithium\action\Dispatcher; use lithium\action\Response; use lithium\net\http\Media; Dispatcher::applyFilter('_callable', function ($self, $params, $chain) { list($library, $asset) = explode('/', $params['request']->url, 2) + array("", ""); if ($asset && ($path = Media::webroot($library)) && file_exists($file = "{$path}/{$asset}")) { return function () use($file) { $info = pathinfo($file); $media = Media::type($info['extension']); $content = (array) $media['content']; return new Response(array('headers' => array('Content-type' => reset($content)), 'body' => file_get_contents($file))); }; } return $chain->next($self, $params, $chain); }); Media::type('js', array('application/javascript', 'text/javascript'), array('view' => 'lithium\\template\\View', 'paths' => array('template' => '{:library}/views/{:controller}/{:template}.{:type}.php', 'layout' => '{:library}/views/layouts/{:layout}.{:type}.php', 'element' => array('{:library}/views/elements/{:template}.{:type}.php', '{:library}/views/elements/{:template}.html.php'))));
<?php use lithium\action\Dispatcher; use lithium\net\http\Media; Dispatcher::applyFilter('_callable', function ($self, $params, $chain) { Media::type('default', null, array('theme' => 'default', 'view' => 'li3_themes\\template\\View', 'paths' => array('layout' => '{:library}/webroot/themes/{:theme}/views/layouts/{:layout}.{:type}.php', 'template' => '{:library}/webroot/themes/{:theme}/views/{:controller}/{:template}.{:type}.php', 'element' => '{:library}/webroot/themes/{:theme}/views/elements/{:template}.{:type}.php'), 'webroot' => '{:library}/webroot/themes/{:theme}')); Media::assets('img', array('paths' => array('{:base}/themes/{:theme}/img/{:path}' => array('base', 'theme', 'path')), 'theme' => 'default')); Media::assets('js', array('paths' => array('{:base}/themes/{:theme}/js/{:path}' => array('base', 'theme', 'path')), 'theme' => 'default')); Media::assets('css', array('paths' => array('{:base}/themes/{:theme}/css/{:path}' => array('base', 'theme', 'path')), 'theme' => 'default')); return $chain->next($self, $params, $chain); });
<?php /** * li3_markdown: lithium port to PHP Markdown for parsing markdown markup into HTML. * * @copyright Copyright 2011, Tobias Sandelius (http://sandelius.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ use lithium\util\String; use lithium\core\Libraries; use lithium\net\http\Media; /** * Include PHP Markdown class file */ if (!class_exists('Markdown_Parser', false)) { require_once dirname(__DIR__) . '/vendors/PHPMarkdown/markdown.php'; } Media::type('md', 'text/html', array('view' => '\\lithium\\template\\View', 'renderer' => '\\li3_markdown\\template\\view\\adapter\\Markdown', 'loader' => '\\li3_markdown\\template\\view\\adapter\\Markdown', 'paths' => array('template' => array('{:library}/views/{:controller}/{:template}.{:type}.php', LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.php'), 'layout' => array('{:library}/views/layouts/{:layout}.{:type}.php', LITHIUM_APP_PATH . '/views/layouts/{:layout}.{:type}.php'))));
* intuitive way, using closures and SPL interfaces. The `to()` method allows a `Collection` (or * subclass) to be converted to another format, such as an array. The `Collection` class also allows * other classes to be connected as handlers to convert `Collection` objects to other formats. * * The following connects the `Media` class as a format handler, which allows `Collection`s to be * exported to any format with a handler provided by `Media`, i.e. JSON. This enables things like * the following: * {{{ * $posts = Post::find('all'); * return $posts->to('json'); * }}} */ use lithium\util\Collection; use lithium\net\http\Media; Collection::formats('lithium\\net\\http\\Media'); Media::type('csv', 'text/csv'); /** * This filter is a convenience method which allows you to automatically route requests for static * assets stored within active plugins. For example, given a JavaScript file `bar.js` inside the * `li3_foo` plugin installed in an application, requests to `http://app/path/li3_foo/js/bar.js` * will be routed to `/path/to/app/libraries/plugins/li3_foo/webroot/js/bar.js` on the filesystem. * In production, it is recommended that you disable this filter in favor of symlinking each * plugin's `webroot` directory into your main application's `webroot` directory, or adding routing * rules in your web server's configuration. */ // use lithium\action\Dispatcher; // use lithium\action\Response; // use lithium\net\http\Media; // // Dispatcher::applyFilter('_callable', function($self, $params, $chain) { // list($library, $asset) = explode('/', $params['request']->url, 2) + array("", "");
public function testContentNegotiationByUserAgent() { Media::type('iphone', 'application/xhtml+xml', array('conditions' => array('mobile' => true))); $request = new Request(array('env' => array('HTTP_USER_AGENT' => 'Safari', 'HTTP_ACCEPT' => 'application/xhtml+xml,text/html'))); $this->assertEqual('html', Media::negotiate($request)); $request = new Request(array('env' => array('HTTP_USER_AGENT' => 'iPhone', 'HTTP_ACCEPT' => 'application/xhtml+xml,text/html'))); $this->assertEqual('iphone', Media::negotiate($request)); }
<?php use lithium\core\Libraries; use lithium\net\http\Media; /** * This is the path to the li3_twig plugin, used for Libraries path resolution. */ define('LI3_TWIG_PATH', dirname(__DIR__)); /** * Register the Twig media type. * The default renderer is still accessible if needed. (default exception handling for example). */ Media::type('twig', array('text/html', 'application/xhtml+xml', '*/*'), array('view' => 'li3_twig\\template\\View', 'loader' => 'li3_twig\\template\\Loader', 'renderer' => 'li3_twig\\template\\view\\adapter\\Twig', 'paths' => array('template' => array('{:library}/views/{:controller}/{:template}.html.twig', '{:library}/views/layouts'))));
$base = isset($config['url']) ? $config['url'] : '/docs'; /** * Handles broken URL parsers by matching method URLs with no closing ) and redirecting. */ Router::connect("{$base}/{:args}\\(", array(), function ($request) { return new Response(array('location' => "{$request->url})")); }); Router::connect($base, array('controller' => 'li3_docs.ApiBrowser', 'action' => 'index')); Router::connect("{$base}/{:lib}/{:args}", array('controller' => 'li3_docs.ApiBrowser', 'action' => 'view')); Router::connect('/li3_docs/{:path:js|css}/{:file}.{:type}', array(), function ($request) { $req = $request->params; $file = dirname(__DIR__) . "/webroot/{$req['path']}/{$req['file']}.{$req['type']}"; if (!file_exists($file)) { return; } return new Response(array('body' => file_get_contents($file), 'headers' => array('Content-type' => str_replace(array('css', 'js'), array('text/css', 'text/javascript'), $req['type'])))); }); Router::connect('/li3_docs/{:path:img}/{:args}.{:type}', array(), function ($request) { $req = $request->params; $path = implode('/', $req['args']); $file = dirname(__DIR__) . "/webroot/{$req['path']}/{$path}.{$req['type']}"; if (!file_exists($file)) { return; } $media = Media::type($req['type']); $content = (array) $media['content']; return new Response(array('body' => file_get_contents($file), 'headers' => array('Content-type' => reset($content)))); }); Router::connect('/li3_docs/search/{:query}', array('controller' => 'li3_docs.ApiSearch', 'action' => 'query')); Router::connect(new Locale(array('template' => $base, 'params' => array('controller' => 'li3_docs.ApiBrowser')))); Router::connect(new Locale(array('template' => "{$base}/{:lib}/{:args}", 'params' => array('controller' => 'li3_docs.ApiBrowser', 'action' => 'view'))));
* the following: * {{{ * $posts = Post::find('all'); * return $posts->to('json'); * }}} */ use lithium\util\Collection; Collection::formats('lithium\\net\\http\\Media'); // Mount assets directory as DOMAIN/assets // Stamp assets with version. use lithium\net\http\Media; Media::attach('app', array('path' => dirname(LITHIUM_APP_PATH) . '/assets', 'prefix' => 'assets/v:' . PROJECT_VERSION_BUILD)); // Set default scope. Media::scope('app'); // Render libary views in the app's layout only. Media::type('default', null, array('view' => 'lithium\\template\\View', 'paths' => array('template' => '{:library}/views/{:controller}/{:template}.{:type}.php', 'layout' => LITHIUM_APP_PATH . '/views/layouts/{:layout}.{:type}.php', 'element' => '{:library}/views/elements/{:template}.{:type}.php'))); /** * This filter is a convenience method which allows you to automatically route requests for static * assets stored within active plugins. For example, given a JavaScript file `bar.js` inside the * `li3_foo` plugin installed in an application, requests to `http://app/path/li3_foo/js/bar.js` * will be routed to `/path/to/app/libraries/plugins/li3_foo/webroot/js/bar.js` on the filesystem. * In production, it is recommended that you disable this filter in favor of symlinking each * plugin's `webroot` directory into your main application's `webroot` directory, or adding routing * rules in your web server's configuration. */ // use lithium\action\Dispatcher; // use lithium\action\Response; // use lithium\net\http\Media; // // Dispatcher::applyFilter('_callable', function($self, $params, $chain) { // $url = ltrim($params['request']->url, '/');
<?php use lithium\net\http\Media; require dirname(__DIR__) . '/libraries/mustache/Mustache.php'; Media::type('mustache', 'text/x-mustache', array('view' => 'lithium\\template\\View', 'loader' => 'Mustache', 'renderer' => 'Mustache', 'paths' => array('template' => '{:library}/views/{:controller}/{:template}.{:type}', 'layout' => '{:library}/views/layouts/{:layout}.{:type}', 'element' => '{:library}/views/elements/{:template}.{:type}')));
/** * Tests that the `Response` object can be directly modified from a templating class or encode * function. * * @return void */ public function testResponseModification() { Media::type('my', 'text/x-my', array('view' => 'lithium\\tests\\mocks\\net\\http\\Template')); $response = new Response(); Media::render($response, null, array('type' => 'my')); $this->assertEqual('Value', $response->headers('Custom')); }
} list($library, $asset) = explode('/', $request, 2) + array("", ""); if ($asset && ($path = Media::webroot($library)) && file_exists($file = "{$path}/{$asset}")) { return function () use($file) { $info = pathinfo($file); if ($info['extension'] == "php") { include $file; return false; } $media = Media::type($info['extension']); $content = (array) $media['content']; return new Response(array('headers' => array('Content-type' => reset($content)), 'body' => file_get_contents($file))); }; } return $chain->next($self, $params, $chain); }); Media::type('json', 'application/json', array('layout' => false, 'encode' => 'json_encode', 'decode' => 'json_decode')); Media::type('ajax', array('application/x-www-form-urlencoded; charset=UTF-8', 'text/html'), array('view' => 'lithium\\template\\View', 'paths' => array('template' => array('{:library}/views/{:controller}/{:template}.ajax.php', '{:library}/views/{:controller}/{:template}.html.php'), 'element' => array('{:library}/views/elements/{:template}.ajax.php', '{:library}/views/elements/{:template}.html.php'), 'layout' => '{:library}/views/layouts/default.ajax.php'), 'conditions' => array('ajax' => true))); /* Media::type('upload', array('application/xhtml+xml', 'text/html'), array( 'view' => 'lithium\template\View', 'paths' => array( 'template' => array( '{:library}/views/{:controller}/{:template}.upload.php', '{:library}/views/{:controller}/{:template}.html.php' ), 'layout' => '{:library}/views/layouts/default.upload.php' ), 'conditions' => array('ajax' => true) )); */
Collection::formats('lithium\\net\\http\\Media'); /** * This filter is a convenience method which allows you to automatically route requests for static * assets stored within active plugins. For example, given a JavaScript file `bar.js` inside the * `li3_foo` plugin installed in an application, requests to `http://app/path/li3_foo/js/bar.js` * will be routed to `/path/to/app/libraries/plugins/li3_foo/webroot/js/bar.js` on the filesystem. * In production, it is recommended that you disable this filter in favor of symlinking each * plugin's `webroot` directory into your main application's `webroot` directory, or adding routing * rules in your web server's configuration. */ use lithium\action\Dispatcher; use lithium\core\Libraries; use lithium\net\http\Media; Dispatcher::applyFilter('_callable', function ($self, $params, $chain) { list($plugin, $asset) = explode('/', $params['request']->url, 2) + array("", ""); if ($asset && ($library = Libraries::get($plugin))) { $asset = "{$library['path']}/webroot/{$asset}"; if (file_exists($asset)) { return function () use($asset) { $info = pathinfo($asset); $type = Media::type($info['extension']); header("Content-type: {$type['content']}"); return file_get_contents($asset); }; } } return $chain->next($self, $params, $chain); }); Media::type('jpg', 'image/jpeg', array('cast' => false, 'encode' => function ($data) { return $data['photo']->file->getBytes(); }));
protected function _scaffoldPaths($field = null) { Media::type('default', null, array('view' => 'lithium\\template\\View', 'paths' => array('template' => array(LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.php', RADIUM_PATH . '/views/{:controller}/{:template}.{:type}.php', '{:library}/views/scaffold/{:template}.{:type}.php', RADIUM_PATH . '/views/scaffold/{:template}.{:type}.php', '{:library}/views/{:controller}/{:template}.{:type}.php'), 'layout' => array(LITHIUM_APP_PATH . '/views/layouts/{:layout}.{:type}.php', RADIUM_PATH . '/views/layouts/{:layout}.{:type}.php', '{:library}/views/layouts/{:layout}.{:type}.php'), 'element' => array(LITHIUM_APP_PATH . '/views/elements/{:template}.{:type}.php', RADIUM_PATH . '/views/elements/{:template}.{:type}.php', '{:library}/views/elements/{:template}.{:type}.php'), 'widget' => array(LITHIUM_APP_PATH . '/views/widgets/{:template}.{:type}.php', RADIUM_PATH . '/views/widgets/{:template}.{:type}.php', '{:library}/views/widgets/{:template}.{:type}.php')))); }
<?php use lithium\core\Libraries; use lithium\action\Dispatcher; use lithium\net\http\Media; use li3_amf\extensions\media\Amf; /* * Load Zend Framework Libraries (for AMF encoding and decoding). * http://rad-dev.org/lithium/wiki/guides/using/zend * * 'path' should be set to the location of the Zend folder. * 'includePath' should be set to the loation of folder containing the Zend folder. * */ if (!Libraries::get('Zend')) { Libraries::add("Zend", array("prefix" => "Zend_", 'path' => '/Library/Webserver/Documents/lithium/libraries/Zend', "includePath" => '/Library/Webserver/Documents/lithium/libraries', "bootstrap" => "Loader/Autoloader.php", "loader" => array("Zend_Loader_Autoloader", "autoload"), "transform" => function ($class) { return str_replace("_", "/", $class) . ".php"; })); } /** * Declare AMF media type. */ Media::type('amf', 'application/x-amf', array('decode' => function ($data) { $amf = new Amf(); $response = $amf->processResponseBodies(); $response->finalize(); die(print_r(debug_backtrace(), 1)); return $response; }, 'encode' => function ($data) { return $data; }, 'view' => false));
<?php use lithium\core\Libraries; use lithium\net\http\Media; /** * This is the path to the li3_twig plugin, used for Libraries path resolution. */ define('LI3_TWIG_PATH', dirname(__DIR__)); /** * Add the Twig libraries */ Libraries::add('Twig', array('path' => LI3_TWIG_PATH . '/libraries/Twig/lib/Twig', 'prefix' => 'Twig_', 'loader' => 'Twig_Autoloader::autoload')); /** * Add Twig to recognized media types. */ Media::type('default', null, array('view' => 'lithium\\template\\View', 'loader' => 'li3_twig\\template\\Loader', 'renderer' => 'li3_twig\\template\\view\\adapter\\Twig', 'paths' => array('template' => '{:library}/views/{:controller}/{:template}.{:type}.twig', 'layout' => '{:library}/views/layouts/{:layout}.{:type}.twig')));
<?php use lithium\core\Libraries; use lithium\core\ConfigException; use lithium\template\View; use lithium\net\http\Media; // Define path to plugin and other constants defined('LI3_HIERARCHY_PATH') or define('LI3_HIERARCHY_PATH', dirname(__DIR__)); /** * Map to the new renderer */ Media::type('default', null, array('view' => '\\lithium\\template\\View', 'renderer' => '\\li3_hierarchy\\template\\view\\adapter\\Hierarchy', 'paths' => array('template' => array(LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.php', '{:library}/views/{:controller}/{:template}.{:type}.php'), 'layout' => array(LITHIUM_APP_PATH . '/views/{:controller}/{:layout}.{:type}.php', '{:library}/views/{:controller}/{:layout}.{:type}.php')))); Media::applyFilter('view', function ($self, $params, $chain) { if (isset($params['handler']['renderer']) && array_slice(explode('\\', $params['handler']['renderer']), -1, 1) == array('Hierarchy')) { $params['handler']['processes'] = array('all' => array('template'), 'template' => array('template'), 'element' => array('element')); } return $chain->next($self, $params, $chain); });
/** * Tests handling content type manually using parameters to `Media::render()`, for content types * that are registered but have no default handler. * * @return void */ public function testManualContentHandling() { Media::type('custom', 'text/x-custom'); $response = new Response(); $response->type = 'custom'; Media::render($response, 'Hello, world!', array('layout' => false, 'template' => false, 'encode' => function ($data) { return "Message: {$data}"; })); $result = $response->body; $expected = array("Message: Hello, world!"); $this->assertEqual($expected, $result); $this->expectException("/Template not found/"); Media::render($response, 'Hello, world!'); $result = $response->body; $this->assertNull($result); }