Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP clarification on using set() and compact() together. Will only work w/ compact()

I know compact() is a standard php function. And set() is a cake-specific method.

I am running a simple test of passing a value to a view generated with ajax (user render() in my controller), and it only passes the value from the controller to the view if my setup is like so:

$variable_name_to_pass = "Passing to the view using set() can compact()";

$this->set(compact('variable_name_to_pass'));

From reading the manual, it appears set() should work along w/out compact.

Can anyone explain why set() will not work alone? Like

$this->set('variable_name_to_pass');
like image 775
OldWest Avatar asked Mar 29 '11 19:03

OldWest


People also ask

What is compact CakePHP?

The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values.

What does compact () do in laravel?

The compact() function is used to convert given variable to to array in which the key of the array will be the name of the variable and the value of the array will be the value of the variable.

What is set in CakePHP?

Array management, if done right, can be a very powerful and useful tool for building smarter, more optimized code. CakePHP offers a very useful set of static utilities in the Set class that allow you to do just that. CakePHP's Set class can be called from any model or controller in the same way Inflector is called.


1 Answers

According to the CakePHP API:

Parameters:

mixed $one required

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.

The compact function returns an associative array, built by taking the names specified in the input array, using them as keys, and taking the values of the variables referenced by those names and making those the values. For example:

$fred = 'Fred Flinstone';
$barney = 'Barney Rubble';
$names = compact('fred', 'barney');

// $names == array('fred' => 'Fred Flinstone', 'barney' => 'Barney Rubble')

So when you use compact in conjunction with set, you're using the single parameter form of the set function, by passing it an associative array of key-value pairs.

If you just have one variable you want to set on the view, and you want to use the single parameter form, you must invoke set in the same way:

$variable_to_pass = 'Fred';
$this->set(compact('variable_to_pass'));

Otherwise, the two parameter form of set can be used:

$variable_to_pass = 'Fred';
$this->set('variable_to_pass', $variable_to_pass);

Both achieve the same thing.

like image 71
tokes Avatar answered Sep 25 '22 01:09

tokes