Wednesday, March 16, 2022

[FIXED] CakePHP : Why they use className with first brackates ()?

Issue

I have used a cakephp method to change layout. Here it's looking like

$this->viewBuilder()->setLayout('admin');

I have seen viewBuilder Class, where they haven't use any construct. Then for calling method setLayout why do I need to use className like viewBuilder(). At first I thought it's a nested method, but it's not.


Solution

Looking at the API at cake.org, you can see that method(not class) viewBuilder() is defined in trait ViewVarsTrait and returns a ViewBuilder object (i.e. gets you the view builder being used).

This ViewBuilder object has access to method setLayout().

This is why you use: $this->viewBuilder()->setLayout('admin');

from source at cakephp.org

 26: trait ViewVarsTrait
 27: {
     ...
/**
 52:      * Get the view builder being used.
 53:      *
 54:      * @return \Cake\View\ViewBuilder
 55:      */
 56:     public function viewBuilder()
 57:     {
 58:         if (!isset($this->_viewBuilder)) {
 59:             $this->_viewBuilder = new ViewBuilder();
 60:         }
 61: 
 62:         return $this->_viewBuilder;
 63:     }
     ...

note: for more info on what traits are and how to use them.



Answered By - lovelace

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.