A view class that is used for JSON responses.
By setting the '_serialize' key in your controller, you can specify a view variable that should be serialized to JSON and used as the response for the request. This allows you to omit views and layouts if you just need to emit a single view variable as the JSON response.
In your controller, you could do the following:
$this->set(array('posts' => $posts, '_serialize' => 'posts'));
When the view is rendered, the $posts
view variable will be serialized into JSON.
You can also define '_serialize'
as an array. This will create a top level object containing all the named view variables:
$this->set(compact('posts', 'users', 'stuff')); $this->set('_serialize', array('posts', 'users'));
The above would generate a JSON object that looks like:
{"posts": [...], "users": [...]}
If you don't use the _serialize
key, you will need a view. You can use extended views to provide layout-like functionality.
You can also enable JSONP support by setting parameter _jsonp
to true or a string to specify custom query string paramater name which will contain the callback function name.
__construct( Controller $controller null )
Constructor
Controller
$controller
optional null View::__construct()
_serialize( array $serialize )
Serialize view vars
_jsonOptions
You can set custom options for json_encode() this way, e.g. JSON_HEX_TAG | JSON_HEX_APOS
.
$serialize
string
CakeException
loadHelpers( )
Skip loading helpers if this is a _serialize based view.
View::loadHelpers()
render( string $view null , string $layout null )
Render a JSON view.
_serialize
To convert a set of view variables into a JSON response. Its value can be a string for single variable name or array for multiple names. You can omit the_serialize
parameter, and use a normal view + layout as well. _jsonp
Enables JSONP support and wraps response in callback function provided in query string. - Setting it to true enables the default query string parameter "callback". - Setting it to a string value, uses the provided query string parameter for finding the JSONP callback name.
$view
optional null $layout
optional null string
CakeException
View::render()
__get( string $name )
Magic accessor for helpers. Provides access to attributes that were deprecated.
$name
mixed
__isset( string $name )
Magic isset check for deprecated attributes.
$name
boolean
__set( string $name , mixed $value )
Magic accessor for deprecated attributes.
$name
$value
mixed
_elementCache( string $name , string $data , array $options )
Checks if an element is cached and returns the cached data if present
$name
$data
$options
string|null
_evaluate( string $viewFile , array $dataForView )
Sandbox method to evaluate a template / view script in.
$viewFile
$dataForView
string
_getElementFileName( string $name )
Finds an element filename, returns false on failure.
$name
mixed
_getExtensions( )
Get the extensions that view files can use.
array
_getLayoutFileName( string $name null )
Returns layout filename for this template as a string.
$name
optional null string
MissingLayoutException
_getViewFileName( string $name null )
Returns filename of given action's template file (.ctp) as a string. CamelCased action names will be under_scored! This means that you can have LongActionNames that refer to long_action_names.ctp views.
$name
optional null string
MissingViewException
_paths( string $plugin null , boolean $cached true )
Return all possible paths to find view files in order
$plugin
optional null $cached
optional true array
_render( string $viewFile , array $data array() )
Renders and returns output for given view filename with its array of data. Handles parent/extended views.
$viewFile
$data
optional array() string
CakeException
_renderElement( string $file , array $data , array $options )
Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used
$file
$data
$options
string
addScript( string $name , string $content null )
Adds a script block or other element to be inserted in $scripts_for_layout in the <head />
of a document layout
$name
$content
optional null View::start()
append( string $name , mixed $value null )
Append to an existing or new block. Appending to a new block will create the block.
$name
$value
optional null ViewBlock::concat()
assign( string $name , mixed $value )
Set the content for a block. This will overwrite any existing content.
$name
$value
ViewBlock::set()
blocks( )
Get the names of all the existing blocks.
array
ViewBlock::keys()
element( string $name , array $data array() , array $options array() )
Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send data to be used in the element. Elements can be cached improving performance by using the cache
option.
$name
MyPlugin.template
to use the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.$data
optional array() $options
optional array() cache
- Can either be true
, to enable caching using the config in View::$elementCache. Or an array If an array, the following keys can be used: - config
- Used to store the cached element in a custom cache configuration. - key
- Used to define the key used in the Cache::write(). It will be prefixed with element_
- plugin
- (deprecated!) Load an element from a specific plugin. This option is deprecated, and will be removed in CakePHP 3.0. Use Plugin.element_name
instead. - callbacks
- Set to true to fire beforeRender and afterRender helper callbacks for this element. Defaults to false. - ignoreMissing
- Used to allow missing elements. Set to true to not trigger notices.string
elementExists( string $name )
Checks if an element exists
$name
MyPlugin.template
to check the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.boolean
exists( string $name )
Check if a block exists
$name
boolean
extend( string $name )
Provides view or element extension/inheritance. Views can extends a parent view and populate blocks in the parent template.
$name
LogicException
LogicException
fetch( string $name , string $default '' )
Fetch the content for a block. If a block is empty or undefined '' will be returned.
$name
$default
optional '' string
ViewBlock::get()
get( string $var , mixed $default null )
Returns the contents of the given View variable.
$var
$default
optional null mixed
getEventManager( )
Returns the CakeEventManager manager instance that is handling any callbacks. You can use this instance to register any new listeners or callbacks to the controller events, or create your own events and trigger them at will.
CakeEventManager
getVar( string $var )
Returns the contents of the given View variable(s)
$var
mixed
getVars( )
Returns a list of variables available in the current View context
array
loadHelper( string $helperName , array $settings array() )
Loads a helper. Delegates to the HelperCollection::load()
to load the helper
$helperName
$settings
optional array() Helper
HelperCollection::load()
pluginSplit( string $name , boolean $fallback true )
Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
$name
$fallback
optional true array
prepend( string $name , mixed $value null )
Prepend to an existing or new block. Prepending to a new block will create the block.
$name
$value
optional null ViewBlock::concat()
renderCache( string $filename , string $timeStart )
Render cached view. Works in concert with CacheHelper and Dispatcher to render cached view files.
$filename
$timeStart
boolean
renderLayout( string $content , string $layout null )
Renders a layout. Returns output from _render(). Returns false on error. Several variables are created for use in layout.
title_for_layout
- A backwards compatible place holder, you should set this value if you want more control.content_for_layout
- contains rendered view filescripts_for_layout
- Contains content added with addScript() as well as any content in the 'meta', 'css', and 'script' blocks. They are appended in that order.Deprecated features:
$scripts_for_layout
is deprecated and will be removed in CakePHP 3.0. Use the block features instead. meta
, css
and script
will be populated by the matching methods on HtmlHelper.$title_for_layout
is deprecated and will be removed in CakePHP 3.0. Use the title
block instead.$content_for_layout
is deprecated and will be removed in CakePHP 3.0. Use the content
block instead.$content
$layout
optional null mixed
CakeException
set( string|array $one , string|array $two null )
Allows a template or element to set a variable that will be available in a layout or other element. Analogous to Controller::set().
$one
$two
optional null start( string $name )
Start capturing output for a 'block'
$name
ViewBlock::start()
startIfEmpty( string $name )
Start capturing output for a 'block' if it has no content
$name
ViewBlock::startIfEmpty()
uuid( string $object , string $url )
Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
$object
$url
string
_mergeVars( array $properties , string $class , boolean $normalize true )
Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'
This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.
$properties
$class
$normalize
optional true _set( array $properties array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
$properties
optional array() _stop( integer|string $status 0 )
Stop execution of the current script. Wraps exit() making testing easier.
$status
optional 0 dispatchMethod( string $method , array $params array() )
Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array
$method
$params
optional array() mixed
log( string $msg , integer $type LOG_ERR , null|string|array $scope null )
Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
$msg
$type
optional LOG_ERR $scope
optional null boolean
requestAction( string|array $url , array $extra array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
POST and GET data can be simulated in requestAction. Use $extra['url']
for GET data. The $extra['data']
parameter allows POST data simulation.
$url
$extra
optional array() mixed
toString( )
Object-to-string conversion. Each class can override this method as necessary.
string
TYPE_ELEMENT, TYPE_LAYOUT, TYPE_VIEW |
protected string
The currently rendering view file. Used for resolving parent files.
null
protected string
Currently rendering an element. Used for finding parent fragments for elements.
''
protected CakeEventManager
Instance of the CakeEventManager this View object is using to dispatch inner events. Usually the manager is shared with the controller, so it it possible to register view events in the controller layer.
null
protected boolean
Whether the event manager was already configured for this object
false
protected array
The names of views and their parents used with View::extend();
array()
protected array
List of variables to collect from the associated controller.
array( 'viewVars', 'autoLayout', 'ext', 'helpers', 'view', 'layout', 'name', 'theme', 'layoutPath', 'viewPath', 'request', 'plugin', 'passedArgs', 'cacheAction' )
protected array
Content stack, used for nested templates that all use View::extend();
array()
public boolean
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
true
public mixed
Used to define methods a controller that will be cached.
Controller::$cacheAction
false
public string
The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.
View::element()
'default'
public array
Element cache settings
View::_renderElement()
array()
public CakeRequest
An instance of a CakeRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.
public CacheHelper
public FormHelper
public HtmlHelper
public NumberHelper
public PaginatorHelper
public SessionHelper
public TextHelper
public TimeHelper
© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/2.7/class-JsonView.html