I was reading the CakePHP manual on $params and was wondering what the appropriate usage is for each? I know that the array that is returned is slightly different ('url' actually has an array key called 'url' that returns the controller/action, and that 'named' does not. Can someone show an example of why it would be important to use one over the other? (I saw the structure difference in the url as well and didn't know why the difference between key:value and key=value)
TLDR: For CakePHP 2.x: Whether to use params['named'] or params['url'] just depends on what data you're looking for. 'url' returns a string of the entire url after the domain, and 'named' returns an array of any passed "named" variables (comma-separated key:value pairs)
CakePHP 3.x: no 'named' variables
Explained in more depth:
The best way to get an idea of why you'd use one of the other is debug params in a view:
debug($this->params);
You'll see, there is a LOT of data in the params array. For example, with my url: http://www.example.com/dashboards/index/1/2/blah:test
params => array(
'plugin' => null,
'controller' => 'dashboards',
'action' => 'index',
'named' => array(
'blah' => 'test'
),
'pass' => array(
(int) 0 => '1',
(int) 1 => '2'
),
'models' => array(
'Dashboard' => array(
'plugin' => null,
'className' => 'Dashboard'
),
//...
)
)
data => array()
query => array(
'dashboards/index/1/2/blah:test' => ''
)
url => 'dashboards/index/1/2/blah:test'
base => ''
webroot => '/'
here => '/dashboards/index/1/2/blah:test'
As you can see, it has a LOT of data. Your question of "why would you use "named" vs "url" is explained just by looking at the data.
$this->params['url']
returns the STRING 'dashboards/index/1/2/blah:test'
(not very usable in most cases).
$this->params['named']
returns a key/value ARRAY of your named variables (in this case, just one variable): array('blah' => 'test');
(much more usable if that's what we're looking for)
So... the answer is, if you want the named variables, use 'named'
- if you want the end of the URL as a string, use 'url
'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With