CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.1 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • Helper
  • HelperCollection
  • JsonView
  • MediaView
  • ScaffoldView
  • ThemeView
  • View
  • ViewBlock
  • XmlView

Class JsonView

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 + layouts, if your 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.

Object
Extended by View
Extended by JsonView
Package: Cake\View
Since: CakePHP(tm) v 2.1.0
Copyright: Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
License: License (http://www.opensource.org/licenses/mit-license.php)
Location: Cake/View/JsonView.php

Inherited Constants

  • TYPE_ELEMENT, TYPE_LAYOUT, TYPE_VIEW

Properties summary

  • $subDir public
    string

    JSON views are always located in the 'json' sub directory for a controllers views.

Inherited Magic Properties

  • Blocks, Cache, Form, Html, Js, Number, Paginator, Rss, Session, Text, Time

Inherited Properties

  • Blocks, Helpers, _current, _currentType, _eventManager, _eventManagerConfigured, _helpersLoaded, _parents, _passedVars, _paths, _scripts, _stack, autoLayout, cacheAction, elementCache, ext, hasRendered, helpers, layout, layoutPath, name, passedArgs, plugin, request, response, theme, uuids, validationErrors, view, viewPath, viewVars

Method Summary

  • __construct() public
    Constructor
  • render() public
    Render a JSON view.

Method Detail

__construct() public ¶

__construct( Controller $controller = null )

Constructor

Parameters
Controller $controller optional null
Overrides
View::__construct()

render() public ¶

render( string $view = null , string $layout = null )

Render a JSON view.

Uses the special '_serialize' parameter to convert a set of view variables into a JSON response. Makes generating simple JSON responses very easy. You can omit the '_serialize' parameter, and use a normal view + layout as well.

Parameters
string $view optional null
The view being rendered.
string $layout optional null
The layout being rendered.
Returns
string
The rendered view.
Throws
CakeException
if there is an error in the view.
Overrides
View::render()

Methods inherited from View

__get() public ¶

__get( string $name )

Magic accessor for helpers. Provides access to attributes that were deprecated.

Parameters
string $name
Name of the attribute to get.
Returns
mixed

__isset() public ¶

__isset( string $name )

Magic isset check for deprecated attributes.

Parameters
string $name
Name of the attribute to check.
Returns
boolean

__set() public ¶

__set( string $name , string $value )

Magic accessor for deprecated attributes.

Parameters
string $name
Name of the attribute to set.
string $value
Value of the attribute to set.
Returns
mixed

_evaluate() protected ¶

_evaluate( string $___viewFn , array $___dataForView )

Sandbox method to evaluate a template / view script in.

Parameters
string $___viewFn
Filename of the view
array $___dataForView

Data to include in rendered view. If empty the current View::$viewVars will be used.

Returns
string
Rendered output

_getElementFileName() protected ¶

_getElementFileName( string $name )

Finds an element filename, returns false on failure.

Parameters
string $name
The name of the element to find.
Returns
mixed
Either a string to the element filename or false when one can't be found.

_getExtensions() protected ¶

_getExtensions( )

Get the extensions that view files can use.

Returns
array
Array of extensions view files use.

_getLayoutFileName() protected ¶

_getLayoutFileName( string $name = null )

Returns layout filename for this template as a string.

Parameters
string $name optional null
The name of the layout to find.
Returns
string
Filename for layout file (.ctp).
Throws
MissingLayoutException
when a layout cannot be located

_getViewFileName() protected ¶

_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.

Parameters
string $name optional null
Controller action to find template filename for
Returns
string
Template filename
Throws
MissingViewException
when a view file could not be found.

_paths() protected ¶

_paths( string $plugin = null , boolean $cached = true )

Return all possible paths to find view files in order

Parameters
string $plugin optional null
Optional plugin name to scan for view files.
boolean $cached optional true
Set to true to force a refresh of view paths.
Returns
array
paths

_render() protected ¶

_render( string $viewFile , array $data = array() )

Renders and returns output for given view filename with its array of data. Handles parent/extended views.

Parameters
string $viewFile
Filename of the view
array $data optional array()
Data to include in rendered view. If empty the current View::$viewVars will be used.
Returns
string
Rendered output
Throws
CakeException
when a block is left open.

addScript() public deprecated ¶

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

Deprecated
Will be removed in 3.0. Supersceeded by blocks functionality.
Parameters
string $name

Either the key name for the script, or the script content. Name can be used to update/replace a script element.

string $content optional null
The content of the script being added, optional.
See
View::start()

append() public ¶

append( string $name , string $value = null )

Append to an existing or new block. Appending to a new block will create the block.

Parameters
string $name
Name of the block
string $value optional null
The content for the block.
Throws
CakeException
when you use non-string values.
See
ViewBlock::append()

assign() public ¶

assign( string $name , string $value )

Set the content for a block. This will overwrite any existing content.

Parameters
string $name
Name of the block
string $value
The content for the block.
Throws
CakeException
when you use non-string values.
See
ViewBlock::assign()

blocks() public ¶

blocks( )

Get the names of all the existing blocks.

Returns
array
An array containing the blocks.
See
ViewBlock::keys()

element() public deprecated ¶

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.

Deprecated

The $options['plugin'] is deprecated and will be removed in CakePHP 3.0. Use Plugin.element_name instead.


Parameters
string $name

Name of template file in the/app/View/Elements/ folder, or 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.

array $data optional array()
Array of data to be made available to the rendered view (i.e. the Element)
array $options optional array()

Array of options. Possible keys are: - 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 - Load an element from a specific plugin. This option is deprecated, see below. - callbacks - Set to true to fire beforeRender and afterRender helper callbacks for this element. Defaults to false.

Returns
string
Rendered Element

end() public ¶

end( )

End a capturing block. The compliment to View::start()

See
ViewBlock::start()

extend() public ¶

extend( string $name )

Provides view or element extension/inheritance. Views can extends a parent view and populate blocks in the parent template.

Parameters
string $name
The view or element to 'extend' the current one with.
Throws
LogicException
when you extend a view with itself or make extend loops.
LogicException
when you extend an element which doesn't exist

fetch() public ¶

fetch( string $name )

Fetch the content for a block. If a block is empty or undefined '' will be returned.

Parameters
string $name
Name of the block
Returns
The
block content or '' if the block does not exist.
See
ViewBlock::fetch()

get() public ¶

get( string $var )

Returns the contents of the given View variable or a block. Blocks are checked before view variables.

Parameters
string $var
The view var you want the contents of.
Returns
mixed
The content of the named var if its set, otherwise null.

getEventManager() public ¶

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.

Returns
CakeEventManager

getVar() public deprecated ¶

getVar( string $var )

Returns the contents of the given View variable(s)

Deprecated
Will be removed in 3.0 Use View::get() instead.
Parameters
string $var
The view var you want the contents of.
Returns
mixed
The content of the named var if its set, otherwise null.

getVars() public ¶

getVars( )

Returns a list of variables available in the current View context

Returns
array
Array of the set view variable names.

loadHelper() public ¶

loadHelper( string $helperName , array $settings = array() )

Loads a helper. Delegates to the HelperCollection::load() to load the helper

Parameters
string $helperName
Name of the helper to load.
array $settings optional array()
Settings for the helper
Returns
Helper
a constructed helper object.
See
HelperCollection::load()

loadHelpers() public ¶

loadHelpers( )

Interact with the HelperCollection to load all the helpers.

pluginSplit() public ¶

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

Parameters
string $name
The name you want to plugin split.
boolean $fallback optional true
If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
Returns
array
Array with 2 indexes. 0 => plugin name, 1 => filename

renderCache() public ¶

renderCache( string $filename , string $timeStart )

Render cached view. Works in concert with CacheHelper and Dispatcher to render cached view files.

Parameters
string $filename
the cache file to include
string $timeStart
the page render start time
Returns
boolean
Success of rendering the cached file.

renderLayout() public ¶

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 file
  • scripts_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
  • $content_for_layout is deprecated and will be removed in CakePHP 3.0. Use the content block instead.
Parameters
string $content
Content to render in a view, wrapped by the surrounding layout.
string $layout optional null
Layout name
Returns
mixed
Rendered output, or false on error
Throws
CakeException
if there is an error in the view.

set() public ¶

set( mixed $one , mixed $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().

Parameters
mixed $one
A string or an array of data.
mixed $two optional null

Value in case $one is a string (which then works as the key). Unused if $one is an associative array, otherwise serves as the values to $one's keys.

start() public ¶

start( string $name )

Start capturing output for a 'block'

Parameters
string $name
The name of the block to capture for.
See
ViewBlock::start()

uuid() public ¶

uuid( string $object , string $url )

Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.

Parameters
string $object
Type of object, i.e. 'form' or 'link'
string $url
The object's target URL
Returns
string

Methods inherited from Object

_mergeVars() protected ¶

_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.

Parameters
array $properties
The name of the properties to merge.
string $class
The class to merge the property with.
boolean $normalize optional true
Set to true to run the properties through Set::normalize() before merging.

_set() protected ¶

_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.

Parameters
array $properties optional array()
An associative array containing properties and corresponding values.

_stop() protected ¶

_stop( integer|string $status = 0 )

Stop execution of the current script. Wraps exit() making testing easier.

Parameters
integer|string $status optional 0
see http://php.net/exit for values

dispatchMethod() public ¶

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

Parameters
string $method
Name of the method to call
array $params optional array()
Parameter list to use when calling $method
Returns
mixed
Returns the result of the method call

log() public ¶

log( string $msg , integer $type = LOG_ERROR )

Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.

Parameters
string $msg
Log message
integer $type optional LOG_ERROR
Error type constant. Defined in app/Config/core.php.
Returns
boolean
Success of log write

requestAction() public ¶

requestAction( mixed $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()

Passing POST and GET data

POST and GET data can be simulated in requestAction. Use $extra['url'] for GET data. The $extra['data'] parameter allows POST data simulation.

Parameters
mixed $url

String or array-based url. Unlike other url arrays in CakePHP, this url will not automatically handle passed and named arguments in the $url parameter.

array $extra optional array()

if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.

Returns
mixed

Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.


toString() public ¶

toString( )

Object-to-string conversion. Each class can override this method as necessary.

Returns
string
The name of this class

Properties detail

$subDir ¶

public string

JSON views are always located in the 'json' sub directory for a controllers views.

'json'
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs