Fr3nch13/CakePHP Utilities

JsonView extends SerializedView
in package

A view class that is used for JSON responses.

It allows you to omit templates if you just need to emit JSON string as response.

In your controller, you could do the following:

$this->set(['posts' => $posts]);
$this->viewBuilder()->setOption('serialize', true);

When the view is rendered, the $posts view variable will be serialized into JSON.

You can also set multiple view variables for serialization. This will create a top level object containing all the named view variables:

$this->set(compact('posts', 'users', 'stuff'));
$this->viewBuilder()->setOption('serialize', true);

The above would generate a JSON object that looks like:

{"posts": [...], "users": [...]}

You can also set 'serialize' to a string or array to serialize only the specified view variables.

If you don't set the serialize option, you will need a view template. You can use extended views to provide layout-like functionality.

You can also enable JSONP support by setting jsonp option to true or a string to specify custom query string parameter name which will contain the callback function name.

Table of Contents

Constants

NAME_TEMPLATE  = 'templates'
Constant for type used for App::path().
PLUGIN_TEMPLATE_FOLDER  = 'plugin'
Constant for folder name containing files for overriding plugin templates.
TYPE_ELEMENT  = 'element'
Constant for view file type 'element'
TYPE_LAYOUT  = 'layout'
Constant for view file type 'layout'
TYPE_MATCH_ALL  = '_match_all_'
The magic 'match-all' content type that views can use to behave as a fallback during content-type negotiation.
TYPE_TEMPLATE  = 'template'
Constant for view file type 'template'.

Properties

$Blocks  : ViewBlock
$Breadcrumbs  : BreadcrumbsHelper
$Flash  : FlashHelper
$Form  : FormHelper
$Html  : HtmlHelper
$Number  : NumberHelper
$Paginator  : PaginatorHelper
$Text  : TextHelper
$Time  : TimeHelper
$Url  : UrlHelper
$_config  : array<string, mixed>
Runtime config
$_configInitialized  : bool
Whether the config property has already been configured with defaults
$_current  : string
The currently rendering view file. Used for resolving parent files.
$_currentType  : string
Currently rendering an element. Used for finding parent fragments for elements.
$_defaultConfig  : array<string, mixed>
Default config options.
$_eventClass  : string
Default class name for new event objects.
$_eventManager  : EventManagerInterface|null
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
$_ext  : string
File extension. Defaults to ".php".
$_helpers  : HelperRegistry
Helpers collection
$_parents  : array<string|int, string>
The names of views and their parents used with View::extend();
$_passedVars  : array<string|int, string>
List of variables to collect from the associated controller.
$_paths  : array<string|int, string>
Holds an array of paths.
$_pathsForPlugin  : array<string|int, array<string|int, string>>
Holds an array of plugin paths.
$_responseType  : string
Response type.
$_stack  : array<string|int, string>
Content stack, used for nested templates that all use View::extend();
$_viewBlockClass  : string
ViewBlock class.
$autoLayout  : bool
Turns on or off CakePHP's conventional mode of applying layout files. On by default.
$Blocks  : ViewBlock
ViewBlock instance.
$elementCache  : 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.
$helpers  : array<string|int, mixed>
An array of names of built-in helpers to include.
$layout  : string
The name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
$layoutPath  : string
JSON layouts are located in the JSON subdirectory of `Layouts/`
$name  : string
Name of the controller that created the View if any.
$plugin  : string|null
The name of the plugin.
$request  : ServerRequest
An instance of a \Cake\Http\ServerRequest object that contains information about the current request.
$response  : Response
Reference to the Response object
$subDir  : string
JSON views are located in the 'json' subdirectory for controllers' views.
$template  : string
The name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
$templatePath  : string
The name of the subfolder containing templates for this View.
$theme  : string|null
The view theme to use.
$viewVars  : array<string, mixed>
An array of variables

Methods

__construct()  : mixed
Constructor
__get()  : Helper|null
Magic accessor for helpers.
append()  : $this
Append to an existing or new block.
assign()  : $this
Set the content for a block. This will overwrite any existing content.
blocks()  : array<string|int, string>
Get the names of all the existing blocks.
cache()  : string
Create a cached block of view logic.
configShallow()  : $this
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
contentType()  : string
Mime-type this view class renders as.
disableAutoLayout()  : $this
Turns off CakePHP's conventional mode of applying layout files.
dispatchEvent()  : EventInterface
Wrapper for creating and dispatching events.
element()  : string
Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
elementExists()  : bool
Checks if an element exists
enableAutoLayout()  : $this
Turns on or off CakePHP's conventional mode of applying layout files.
end()  : $this
End a capturing block. The compliment to View::start()
exists()  : bool
Check if a block exists
extend()  : $this
Provides template or element extension/inheritance. Templates can extends a parent template and populate blocks in the parent template.
fetch()  : string
Fetch the content for a block. If a block is empty or undefined '' will be returned.
get()  : mixed
Returns the contents of the given View variable.
getConfig()  : mixed
Get config value.
getConfigOrFail()  : mixed
Returns the config for this specific key.
getCurrentType()  : string
Retrieve the current template type
getEventManager()  : EventManagerInterface
Returns the Cake\Event\EventManager manager instance for this object.
getLayout()  : string
Get the name of the layout file to render the template inside of.
getLayoutPath()  : string
Get path for layout files.
getName()  : string
Returns the View's controller name.
getPlugin()  : string|null
Returns the plugin name.
getRequest()  : ServerRequest
Gets the request instance.
getResponse()  : Response
Gets the response instance.
getSubDir()  : string
Get sub-directory for this template files.
getTemplate()  : string
Get the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
getTemplatePath()  : string
Get path for templates files.
getTheme()  : string|null
Get the current view theme.
getVars()  : array<string|int, string>
Returns a list of variables available in the current View context
helpers()  : HelperRegistry
Get the helper registry in use by this View class.
initialize()  : void
Initialization hook method.
isAutoLayoutEnabled()  : bool
Returns if CakePHP's conventional mode of applying layout files is enabled.
loadHelper()  : Helper
Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper
loadHelpers()  : $this
Load helpers only if serialization is disabled.
log()  : bool
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
pluginSplit()  : array<string|int, mixed>
Splits a dot syntax plugin name into its plugin and filename.
prepend()  : $this
Prepend to an existing or new block.
render()  : string
Render a JSON view.
renderLayout()  : string
Renders a layout. Returns output from _render().
reset()  : $this
Reset the content for a block. This will overwrite any existing content.
set()  : $this
Saves a variable or an associative array of variables for use inside a template.
setConfig()  : $this
Sets the config.
setElementCache()  : $this
Set The cache configuration View will use to store cached elements
setEventManager()  : $this
Returns the Cake\Event\EventManagerInterface instance for this object.
setLayout()  : $this
Set the name of the layout file to render the template inside of.
setLayoutPath()  : $this
Set path for layout files.
setPlugin()  : $this
Sets the plugin name.
setRequest()  : $this
Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:
setResponse()  : $this
Sets the response instance.
setSubDir()  : $this
Set sub-directory for this template files.
setTemplate()  : $this
Set the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
setTemplatePath()  : $this
Set path for templates files.
setTheme()  : $this
Set the view theme to use.
start()  : $this
Start capturing output for a 'block'
_checkFilePath()  : string
Check that a view file path does not go outside of the defined template paths.
_configDelete()  : void
Deletes a single config key.
_configRead()  : mixed
Reads a config key.
_configWrite()  : void
Writes a config key.
_createCell()  : Cell
Create and configure the cell instance.
_dataToSerialize()  : mixed
Returns data to be serialized.
_elementCache()  : array<string|int, mixed>
Generate the cache configuration options for an element.
_evaluate()  : string
Sandbox method to evaluate a template / view script in.
_getElementFileName()  : string|false
Finds an element filename, returns false on failure.
_getLayoutFileName()  : string
Returns layout filename for this template as a string.
_getSubPaths()  : array<string|int, string>
Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested.
_getTemplateFileName()  : string
Returns filename of given action's template file as a string.
_inflectTemplateFileName()  : string
Change the name of a view template file into underscored format.
_paths()  : array<string|int, string>
Return all possible paths to find view files in order
_render()  : string
Renders and returns output for given template filename with its array of data. Handles parent/extended templates.
_renderElement()  : string
Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used
_serialize()  : string
Serialize view vars.
cell()  : Cell
Renders the given cell.
getElementPaths()  : Generator
Get an iterator for element paths.
getLayoutPaths()  : Generator
Get an iterator for layout paths.
setContentType()  : void
Set the response content-type based on the view's contentType()

Constants

NAME_TEMPLATE

Constant for type used for App::path().

public string NAME_TEMPLATE = 'templates'

PLUGIN_TEMPLATE_FOLDER

Constant for folder name containing files for overriding plugin templates.

public string PLUGIN_TEMPLATE_FOLDER = 'plugin'

TYPE_ELEMENT

Constant for view file type 'element'

public string TYPE_ELEMENT = 'element'

TYPE_LAYOUT

Constant for view file type 'layout'

public string TYPE_LAYOUT = 'layout'

TYPE_MATCH_ALL

The magic 'match-all' content type that views can use to behave as a fallback during content-type negotiation.

public string TYPE_MATCH_ALL = '_match_all_'

TYPE_TEMPLATE

Constant for view file type 'template'.

public string TYPE_TEMPLATE = 'template'

Properties

$_configInitialized

Whether the config property has already been configured with defaults

protected bool $_configInitialized = false

$_current

The currently rendering view file. Used for resolving parent files.

protected string $_current

$_currentType

Currently rendering an element. Used for finding parent fragments for elements.

protected string $_currentType = ''

$_defaultConfig

Default config options.

protected array<string, mixed> $_defaultConfig = ['serialize' => null, 'jsonOptions' => null, 'jsonp' => null]

Use ViewBuilder::setOption()/setOptions() in your controller to set these options.

  • serialize: Option to convert a set of view variables into a serialized response. Its value can be a string for single variable name or array for multiple names. If true all view variables will be serialized. If null or false normal view template will be rendered.
  • jsonOptions: Options for json_encode(). For e.g. JSON_HEX_TAG | JSON_HEX_APOS.
  • 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.

$_eventClass

Default class name for new event objects.

protected string $_eventClass = \Cake\Event\Event::class

$_ext

File extension. Defaults to ".php".

protected string $_ext = '.php'

$_parents

The names of views and their parents used with View::extend();

protected array<string|int, string> $_parents = []

$_passedVars

List of variables to collect from the associated controller.

protected array<string|int, string> $_passedVars = ['viewVars', 'autoLayout', 'helpers', 'template', 'layout', 'name', 'theme', 'layoutPath', 'templatePath', 'plugin']

$_paths

Holds an array of paths.

protected array<string|int, string> $_paths = []

$_pathsForPlugin

Holds an array of plugin paths.

protected array<string|int, array<string|int, string>> $_pathsForPlugin = []

$_responseType

Response type.

Implement public static contentType(): string instead.

protected string $_responseType

$_stack

Content stack, used for nested templates that all use View::extend();

protected array<string|int, string> $_stack = []

$_viewBlockClass

ViewBlock class.

protected string $_viewBlockClass = \Cake\View\ViewBlock::class
Tags
psalm-var

class-string<\Cake\View\ViewBlock>

$autoLayout

Turns on or off CakePHP's conventional mode of applying layout files. On by default.

protected bool $autoLayout = true

Setting to off means that layouts will not be automatically applied to rendered templates.

$elementCache

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.

protected string $elementCache = 'default'
Tags
see
View::element()

$helpers

An array of names of built-in helpers to include.

protected array<string|int, mixed> $helpers = []

$layout

The name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.

protected string $layout = 'default'

$layoutPath

JSON layouts are located in the JSON subdirectory of `Layouts/`

protected string $layoutPath = 'json'

$name

Name of the controller that created the View if any.

protected string $name = ''

$plugin

The name of the plugin.

protected string|null $plugin

$request

An instance of a \Cake\Http\ServerRequest object that contains information about the current request.

protected ServerRequest $request

This object contains all the information about a request and several methods for reading additional information about the request.

$response

Reference to the Response object

protected Response $response

$subDir

JSON views are located in the 'json' subdirectory for controllers' views.

protected string $subDir = 'json'

$template

The name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.

protected string $template = ''

$templatePath

The name of the subfolder containing templates for this View.

protected string $templatePath = ''

$theme

The view theme to use.

protected string|null $theme

$viewVars

An array of variables

protected array<string, mixed> $viewVars = []

Methods

__construct()

Constructor

public __construct([ServerRequest|null $request = null ][, Response|null $response = null ][, EventManager|null $eventManager = null ][, array<string, mixed> $viewOptions = [] ]) : mixed
Parameters
$request : ServerRequest|null = null

Request instance.

$response : Response|null = null

Response instance.

$eventManager : EventManager|null = null

Event manager instance.

$viewOptions : array<string, mixed> = []

View options. See for list of options which get set as class properties.

__get()

Magic accessor for helpers.

public __get(string $name) : Helper|null
Parameters
$name : string

Name of the attribute to get.

Return values
Helper|null

append()

Append to an existing or new block.

public append(string $name[, mixed $value = null ]) : $this

Appending to a new block will create the block.

Parameters
$name : string

Name of the block

$value : mixed = null

The content for the block. Value will be type cast to string.

Tags
see
ViewBlock::concat()
Return values
$this

assign()

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

public assign(string $name, mixed $value) : $this
Parameters
$name : string

Name of the block

$value : mixed

The content for the block. Value will be type cast to string.

Tags
see
ViewBlock::set()
Return values
$this

blocks()

Get the names of all the existing blocks.

public blocks() : array<string|int, string>
Tags
see
ViewBlock::keys()
Return values
array<string|int, string>

An array containing the blocks.

cache()

Create a cached block of view logic.

public cache(callable $block[, array<string, mixed> $options = [] ]) : string

This allows you to cache a block of view output into the cache defined in elementCache.

This method will attempt to read the cache first. If the cache is empty, the $block will be run and the output stored.

Parameters
$block : callable

The block of code that you want to cache the output of.

$options : array<string, mixed> = []

The options defining the cache key etc.

Tags
throws
RuntimeException

When $options is lacking a 'key' option.

Return values
string

The rendered content.

configShallow()

Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.

public configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this

Setting a specific value:

$this->configShallow('key', $value);

Setting a nested value:

$this->configShallow('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

Return values
$this

contentType()

Mime-type this view class renders as.

public static contentType() : string
Return values
string

The JSON content type.

disableAutoLayout()

Turns off CakePHP's conventional mode of applying layout files.

public disableAutoLayout() : $this

Layouts will not be automatically applied to rendered views.

Return values
$this

dispatchEvent()

Wrapper for creating and dispatching events.

public dispatchEvent(string $name[, array<string|int, mixed>|null $data = null ][, object|null $subject = null ]) : EventInterface

Returns a dispatched event.

Parameters
$name : string

Name of the event.

$data : array<string|int, mixed>|null = null

Any value you wish to be transported with this event to it can be read by listeners.

$subject : object|null = null

The object that this event applies to ($this by default).

Return values
EventInterface

element()

Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.

public element(string $name[, array<string|int, mixed> $data = [] ][, array<string, mixed> $options = [] ]) : 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.

Parameters
$name : string

Name of template file in the templates/element/ 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.

$data : array<string|int, mixed> = []

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

$options : array<string, mixed> = []

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_
  • 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 throw exceptions.

  • plugin - setting to false will force to use the application's element from plugin templates, when the plugin has element with same name. Defaults to true

Tags
throws
MissingElementException

When an element is missing and ignoreMissing is false.

psalm-param

array{cache?:array|true, callbacks?:bool, plugin?:string|false, ignoreMissing?:bool} $options

Return values
string

Rendered Element

elementExists()

Checks if an element exists

public elementExists(string $name) : bool
Parameters
$name : string

Name of template file in the templates/element/ folder, or 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.

Return values
bool

Success

enableAutoLayout()

Turns on or off CakePHP's conventional mode of applying layout files.

public enableAutoLayout([bool $enable = true ]) : $this

On by default. Setting to off means that layouts will not be automatically applied to rendered views.

Parameters
$enable : bool = true

Boolean to turn on/off.

Return values
$this

end()

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

public end() : $this
Tags
see
ViewBlock::end()
Return values
$this

exists()

Check if a block exists

public exists(string $name) : bool
Parameters
$name : string

Name of the block

Return values
bool

extend()

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

public extend(string $name) : $this
Parameters
$name : string

The template or element to 'extend' the current one with.

Tags
throws
LogicException

when you extend a template with itself or make extend loops.

throws
LogicException

when you extend an element which doesn't exist

Return values
$this

fetch()

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

public fetch(string $name[, string $default = '' ]) : string
Parameters
$name : string

Name of the block

$default : string = ''

Default text

Tags
see
ViewBlock::get()
Return values
string

The block content or $default if the block does not exist.

get()

Returns the contents of the given View variable.

public get(string $var[, mixed $default = null ]) : mixed
Parameters
$var : string

The view var you want the contents of.

$default : mixed = null

The default/fallback content of $var.

Return values
mixed

The content of the named var if its set, otherwise $default.

getConfig()

Get config value.

public getConfig([string|null $key = null ][, mixed $default = null ]) : mixed

Currently if config is not set it fallbacks to checking corresponding view var with underscore prefix. Using underscore prefixed special view vars is deprecated and this fallback will be removed in CakePHP 4.1.0.

Parameters
$key : string|null = null

The key to get or null for the whole config.

$default : mixed = null

The return value when the key does not exist.

Tags
psalm-suppress

PossiblyNullArgument

Return values
mixed

Config value being read.

getConfigOrFail()

Returns the config for this specific key.

public getConfigOrFail(string $key) : mixed

The config value for this key must exist, it can never be null.

Parameters
$key : string

The key to get.

Tags
throws
InvalidArgumentException
Return values
mixed

Configuration data at the named key

getCurrentType()

Retrieve the current template type

public getCurrentType() : string
Return values
string

getEventManager()

Returns the Cake\Event\EventManager manager instance for this object.

public getEventManager() : EventManagerInterface

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Return values
EventManagerInterface

getLayout()

Get the name of the layout file to render the template inside of.

public getLayout() : string

The name specified is the filename of the layout in templates/layout/ without the .php extension.

Return values
string

getLayoutPath()

Get path for layout files.

public getLayoutPath() : string
Return values
string

getName()

Returns the View's controller name.

public getName() : string
Tags
since
3.7.7
Return values
string

getPlugin()

Returns the plugin name.

public getPlugin() : string|null
Tags
since
3.7.0
Return values
string|null

getSubDir()

Get sub-directory for this template files.

public getSubDir() : string
Tags
see
View::$subDir
since
3.7.0
Return values
string

getTemplate()

Get the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.

public getTemplate() : string
Return values
string

getTemplatePath()

Get path for templates files.

public getTemplatePath() : string
Return values
string

getTheme()

Get the current view theme.

public getTheme() : string|null
Return values
string|null

getVars()

Returns a list of variables available in the current View context

public getVars() : array<string|int, string>
Return values
array<string|int, string>

Array of the set view variable names.

initialize()

Initialization hook method.

public initialize() : void
Tags
inheritDoc

isAutoLayoutEnabled()

Returns if CakePHP's conventional mode of applying layout files is enabled.

public isAutoLayoutEnabled() : bool

Disabled means that layouts will not be automatically applied to rendered views.

Return values
bool

loadHelper()

Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper

public loadHelper(string $name[, array<string, mixed> $config = [] ]) : Helper
Parameters
$name : string

Name of the helper to load.

$config : array<string, mixed> = []

Settings for the helper

Tags
see
HelperRegistry::load()
Return values
Helper

a constructed helper object.

loadHelpers()

Load helpers only if serialization is disabled.

public loadHelpers() : $this
Return values
$this

log()

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

public log(string $message[, string|int $level = LogLevel::ERROR ][, array<string|int, mixed>|string $context = [] ]) : bool
Parameters
$message : string

Log message.

$level : string|int = LogLevel::ERROR

Error level.

$context : array<string|int, mixed>|string = []

Additional log data relevant to this message.

Return values
bool

Success of log write.

pluginSplit()

Splits a dot syntax plugin name into its plugin and filename.

public pluginSplit(string $name[, bool $fallback = true ]) : array<string|int, mixed>

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
$name : string

The name you want to plugin split.

$fallback : bool = true

If true uses the plugin set in the current Request when parsed plugin is not loaded

Tags
psalm-return

array{string|null, string}

Return values
array<string|int, mixed>

Array with 2 indexes. 0 => plugin name, 1 => filename.

prepend()

Prepend to an existing or new block.

public prepend(string $name, mixed $value) : $this

Prepending to a new block will create the block.

Parameters
$name : string

Name of the block

$value : mixed

The content for the block. Value will be type cast to string.

Tags
see
ViewBlock::concat()
Return values
$this

render()

Render a JSON view.

public render([string|null $template = null ][, string|false|null $layout = null ]) : string
Parameters
$template : string|null = null

The template being rendered.

$layout : string|false|null = null

The layout being rendered.

Return values
string

The rendered view.

renderLayout()

Renders a layout. Returns output from _render().

public renderLayout(string $content[, string|null $layout = null ]) : string

Several variables are created for use in layout.

Parameters
$content : string

Content to render in a template, wrapped by the surrounding layout.

$layout : string|null = null

Layout name

Tags
throws
CakeException

if there is an error in the view.

triggers

View.beforeLayout $this, [$layoutFileName]

triggers

View.afterLayout $this, [$layoutFileName]

Return values
string

Rendered output.

reset()

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

public reset(string $name) : $this
Parameters
$name : string

Name of the block

Tags
see
ViewBlock::set()
Return values
$this

set()

Saves a variable or an associative array of variables for use inside a template.

public set(array<string|int, mixed>|string $name[, mixed $value = null ]) : $this
Parameters
$name : array<string|int, mixed>|string

A string or an array of data.

$value : mixed = null

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

Tags
throws
RuntimeException

If the array combine operation failed.

Return values
$this

setConfig()

Sets the config.

public setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this

Usage

Setting a specific value:

$this->setConfig('key', $value);

Setting a nested value:

$this->setConfig('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

$merge : bool = true

Whether to recursively merge or overwrite existing config, defaults to true.

Tags
throws
CakeException

When trying to set a key that is invalid.

Return values
$this

setElementCache()

Set The cache configuration View will use to store cached elements

public setElementCache(string $elementCache) : $this
Parameters
$elementCache : string

Cache config name.

Tags
see
View::$elementCache
since
3.7.0
Return values
$this

setEventManager()

Returns the Cake\Event\EventManagerInterface instance for this object.

public setEventManager(EventManagerInterface $eventManager) : $this

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Parameters
$eventManager : EventManagerInterface

the eventManager to set

Return values
$this

setLayout()

Set the name of the layout file to render the template inside of.

public setLayout(string $name) : $this

The name specified is the filename of the layout in templates/layout/ without the .php extension.

Parameters
$name : string

Layout file name to set.

Return values
$this

setLayoutPath()

Set path for layout files.

public setLayoutPath(string $path) : $this
Parameters
$path : string

Path for layout files.

Return values
$this

setPlugin()

Sets the plugin name.

public setPlugin(string|null $name) : $this
Parameters
$name : string|null

Plugin name.

Tags
since
3.7.0
Return values
$this

setRequest()

Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:

public setRequest(ServerRequest $request) : $this
  • $this->request - To the $request parameter
  • $this->plugin - To the value returned by $request->getParam('plugin')
Parameters
$request : ServerRequest

Request instance.

Return values
$this

setResponse()

Sets the response instance.

public setResponse(Response $response) : $this
Parameters
$response : Response

Response instance.

Return values
$this

setSubDir()

Set sub-directory for this template files.

public setSubDir(string $subDir) : $this
Parameters
$subDir : string

Sub-directory name.

Tags
see
View::$subDir
since
3.7.0
Return values
$this

setTemplate()

Set the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.

public setTemplate(string $name) : $this
Parameters
$name : string

Template file name to set.

Return values
$this

setTemplatePath()

Set path for templates files.

public setTemplatePath(string $path) : $this
Parameters
$path : string

Path for template files.

Return values
$this

setTheme()

Set the view theme to use.

public setTheme(string|null $theme) : $this
Parameters
$theme : string|null

Theme name.

Return values
$this

start()

Start capturing output for a 'block'

public start(string $name) : $this

You can use start on a block multiple times to append or prepend content in a capture mode.

// Append content to an existing block.
$this->start('content');
echo $this->fetch('content');
echo 'Some new content';
$this->end();

// Prepend content to an existing block
$this->start('content');
echo 'Some new content';
echo $this->fetch('content');
$this->end();
Parameters
$name : string

The name of the block to capture for.

Tags
see
ViewBlock::start()
Return values
$this

_checkFilePath()

Check that a view file path does not go outside of the defined template paths.

protected _checkFilePath(string $file, string $path) : string

Only paths that contain .. will be checked, as they are the ones most likely to have the ability to resolve to files outside of the template paths.

Parameters
$file : string

The path to the template file.

$path : string

Base path that $file should be inside of.

Tags
throws
InvalidArgumentException
Return values
string

The file path

_configDelete()

Deletes a single config key.

protected _configDelete(string $key) : void
Parameters
$key : string

Key to delete.

Tags
throws
CakeException

if attempting to clobber existing config

_configRead()

Reads a config key.

protected _configRead(string|null $key) : mixed
Parameters
$key : string|null

Key to read.

_configWrite()

Writes a config key.

protected _configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
$key : array<string, mixed>|string

Key to write to.

$value : mixed

Value to write.

$merge : string|bool = false

True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.

Tags
throws
CakeException

if attempting to clobber existing config

_createCell()

Create and configure the cell instance.

protected _createCell(string $className, string $action, string|null $plugin, array<string, mixed> $options) : Cell
Parameters
$className : string

The cell classname.

$action : string

The action name.

$plugin : string|null

The plugin name.

$options : array<string, mixed>

The constructor options for the cell.

Return values
Cell

_dataToSerialize()

Returns data to be serialized.

protected _dataToSerialize(array<string|int, mixed>|string $serialize) : mixed
Parameters
$serialize : array<string|int, mixed>|string

The name(s) of the view variable(s) that need(s) to be serialized.

Return values
mixed

The data to serialize.

_elementCache()

Generate the cache configuration options for an element.

protected _elementCache(string $name, array<string|int, mixed> $data, array<string, mixed> $options) : array<string|int, mixed>
Parameters
$name : string

Element name

$data : array<string|int, mixed>

Data

$options : array<string, mixed>

Element options

Tags
psalm-return

array{key:string, config:string}

Return values
array<string|int, mixed>

Element Cache configuration.

_evaluate()

Sandbox method to evaluate a template / view script in.

protected _evaluate(string $templateFile, array<string|int, mixed> $dataForView) : string
Parameters
$templateFile : string

Filename of the template.

$dataForView : array<string|int, mixed>

Data to include in rendered view.

Return values
string

Rendered output

_getElementFileName()

Finds an element filename, returns false on failure.

protected _getElementFileName(string $name[, bool $pluginCheck = true ]) : string|false
Parameters
$name : string

The name of the element to find.

$pluginCheck : bool = true
  • if false will ignore the request's plugin if parsed plugin is not loaded
Return values
string|false

Either a string to the element filename or false when one can't be found.

_getLayoutFileName()

Returns layout filename for this template as a string.

protected _getLayoutFileName([string|null $name = null ]) : string
Parameters
$name : string|null = null

The name of the layout to find.

Tags
throws
MissingLayoutException

when a layout cannot be located

throws
RuntimeException
Return values
string

Filename for layout file.

_getSubPaths()

Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested.

protected _getSubPaths(string $basePath) : array<string|int, string>

This is essentially used to find prefixed template paths for elements and layouts.

Parameters
$basePath : string

Base path on which to get the prefixed one.

Return values
array<string|int, string>

Array with all the templates paths.

_getTemplateFileName()

Returns filename of given action's template file as a string.

protected _getTemplateFileName([string|null $name = null ]) : string

CamelCased action names will be under_scored by default. This means that you can have LongActionNames that refer to long_action_names.php templates. You can change the inflection rule by overriding _inflectTemplateFileName.

Parameters
$name : string|null = null

Controller action to find template filename for

Tags
throws
MissingTemplateException

when a template file could not be found.

throws
RuntimeException

When template name not provided.

Return values
string

Template filename

_inflectTemplateFileName()

Change the name of a view template file into underscored format.

protected _inflectTemplateFileName(string $name) : string
Parameters
$name : string

Name of file which should be inflected.

Return values
string

File name after conversion

_paths()

Return all possible paths to find view files in order

protected _paths([string|null $plugin = null ][, bool $cached = true ]) : array<string|int, string>
Parameters
$plugin : string|null = null

Optional plugin name to scan for view files.

$cached : bool = true

Set to false to force a refresh of view paths. Default true.

Return values
array<string|int, string>

paths

_render()

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

protected _render(string $templateFile[, array<string|int, mixed> $data = [] ]) : string
Parameters
$templateFile : string

Filename of the template

$data : array<string|int, mixed> = []

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

Tags
throws
LogicException

When a block is left open.

triggers

View.beforeRenderFile $this, [$templateFile]

triggers

View.afterRenderFile $this, [$templateFile, $content]

Return values
string

Rendered output

_renderElement()

Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used

protected _renderElement(string $file, array<string|int, mixed> $data, array<string, mixed> $options) : string
Parameters
$file : string

Element file path

$data : array<string|int, mixed>

Data to render

$options : array<string, mixed>

Element options

Tags
triggers

View.beforeRender $this, [$file]

triggers

View.afterRender $this, [$file, $element]

Return values
string

_serialize()

Serialize view vars.

protected _serialize(mixed $serialize) : string
Parameters
$serialize : mixed

The name(s) of the view variable(s) that need(s) to be serialized

Tags
inheritDoc
Return values
string

The serialized data.

cell()

Renders the given cell.

protected cell(string $cell[, array<string|int, mixed> $data = [] ][, array<string, mixed> $options = [] ]) : Cell

Example:

// Taxonomy\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('Taxonomy.TagCloud::smallList', ['limit' => 10]);

// App\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('TagCloud::smallList', ['limit' => 10]);

The display action will be used by default when no action is provided:

// Taxonomy\View\Cell\TagCloudCell::display()
$cell = $this->cell('Taxonomy.TagCloud');

Cells are not rendered until they are echoed.

Parameters
$cell : string

You must indicate cell name, and optionally a cell action. e.g.: TagCloud::smallList will invoke View\Cell\TagCloudCell::smallList(), display action will be invoked by default when none is provided.

$data : array<string|int, mixed> = []

Additional arguments for cell method. e.g.: cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2']) maps to View\Cell\TagCloud::smallList(v1, v2)

$options : array<string, mixed> = []

Options for Cell's constructor

Tags
throws
MissingCellException

If Cell class was not found.

Return values
Cell

The cell instance

getElementPaths()

Get an iterator for element paths.

protected getElementPaths(string|null $plugin) : Generator
Parameters
$plugin : string|null

The plugin to fetch paths for.

Return values
Generator

getLayoutPaths()

Get an iterator for layout paths.

protected getLayoutPaths(string|null $plugin) : Generator
Parameters
$plugin : string|null

The plugin to fetch paths for.

Return values
Generator

setContentType()

Set the response content-type based on the view's contentType()

protected setContentType() : void

        
On this page

Search results