Colgate Shu Colgate Shu - 24 days ago 10
PHP Question

In symfony, how can i get Global methods and variables in any Controller?

The scene is, the client (All request like Ajax in my site) will request a json string like that

{"token":"mytoken"}
.PHP receive it by
$request->getContent()
and
json_decode
it. I store it in a variable named
$data
so i can get it in any Controller.

I also create a method to get value by key, code like that

public function input($key, $default = '', $func = '')
{
$ret = '';
if (isset($this->data[$key])) {
$ret = $this->data[$key];
} else {
return $default;
}
if (is_string($func)) {
if (in_array($func, ['int', 'string', 'array'])) {
settype($ret, $func);
return $ret;
}
if ($func)
$ret = call_user_func($func, $ret);
} elseif (is_array($func)) {
if ($func)
$ret = call_user_func_array($func, [$ret]);
}
if (!$ret)
return $default;
return $ret;
}


Although i can reg it to server, but i use it like that
$this->get('input')->input($mykey);
, this will appear in any controller. Is this a proposed solution?
The question just my title, HOW? Save me .

Answer

If a method is in controller, then you can add $request object to params:

use Symfony\Component\HttpFoundation\Request;
//...
public function input(Request $request, $key, $default = '', $func = '')
//...

Request object has all global vars. More info: http://symfony.com/doc/current/introduction/http_fundamentals.html#symfony-request-object

Comments