简体   繁体   中英

getParam() always returns null

I'm trying to get the project id from the url using the router. Let's say this is my URL: http://boardash.test/tasks/all/7 and I want to get the 7 in my controller.

I created a router using this:

$router->add(
    '/tasks/:action/{project}',
    [
        'controller' => 'tasks',
        ':action'    => 1
    ]
);

And try to access it using:

$this->dispatcher->getParam('project');

But when I var_dump() this, it returns null

What am I missing?

The :action placeholder is not correct. Try like this:

$router->add(
    '/tasks/:action/{project}',
    [
        'controller' => 'tasks',
        'action'    => 1 // <-- Look here
    ]
);

UPDATE: after few tests it seems that it is a bug in the mixed array/short syntax when the named parameter is at the end of the route.

This works as intended and returns correct parameters.

// Test url: /misc/4444444/view
$router->add('/misc/{project}/:action', ['controller' => 'misc', 'action' => 2])

However this does not return correct value for {project} . It returns "view" instead of "4444444".

// Test url: /misc/view/4444444
$router->add('/misc/:action/{project}', ['controller' => 'misc', 'action' => 1])

Syntax explained in the docs: https://docs.phalconphp.com/en/3.2/routing#defining-mixed-parameters

I will investigate a little further later, but you may consider submitting an issue on github meanwhile.


Temporary solution: meanwhile you can use this workaround if it's urgent.

$router->add('/:controller/:action/:params', ['controller' => 1, 'action' => 2, 'params' => 3])

// Test url: misc/view/test-1/test-2/test-3
$this->dispatcher->getParams() // array of all
$this->dispatcher->getParam(0) // test-1
$this->dispatcher->getParam(1) // test-2
$this->dispatcher->getParam(3) // test-3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM