Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between $this->params['url'] and $this->params['named']

Tags:

cakephp

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)

like image 878
huzzah Avatar asked Dec 27 '22 04:12

huzzah


1 Answers

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

like image 169
Dave Avatar answered Feb 16 '23 11:02

Dave