5

I am writing a interceptor to validate request and decode data received from POST. After decoding data I have to set data to $_POST so that my all previous writer functionality will work as it is.

I have set values like below

$_POST['amount'] = $data['a'];
$_POST['currency'] = $data['c'];

I am able to get these variables using $_POST but these values are not accessible in Yii::$app->request->post()

So my question is can I get these values by Yii::$app->request->post()

rob006
  • 21,383
  • 5
  • 53
  • 74
Aabir Hussain
  • 1,161
  • 1
  • 11
  • 29

3 Answers3

7

Post data is cached inside of Request component, so any changes in $_POST will not be reflected in Yii::$app->request->post(). However you may use setBodyParams() to reset this cache:

Yii::$app->request->setBodyParams(null);

$post = Yii::$app->request->post();

Or just use setBodyParams() to set your data directly without touching $_POST:

Yii::$app->request->setBodyParams(['amount' => $data['a'], 'currency' => $data['c']]);
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
rob006
  • 21,383
  • 5
  • 53
  • 74
0

I think you should consider refactoring your code a bit, especially if you are not the only person working on the project because artificially adding values to $_POST is just confusing and should be avoided, if possible. If I see a code that reads a variable from $_POST, I go looking for it being set on the frontend not somewhere in the controller.

You could make your interceptor do:

$post = Yii::$app->request->post();
// or $post = _ $POST;
$post['foo'] = 'bar';
someNamespace::$writeData = $post;

Then when you want to access the data (assuming it doesn't always go through the interceptor and needs to be initialized when empty):

if (empty(someNamespace::$writeData)) {
    someNamespace::$writeData = $_POST;
}
$data = someNamespace::$writeData;

and read everything from that static variable instead of $_POST. It's neater and much more maintanable code, IMHO.

0

Just to extend on the accepted answer of @rob006, in response to the comment below that by Budi Mulyo.

You can add to the post data by doing the following:

    $params = Yii::$app->request->getBodyParams();
    $params['somethingToAdd'] = 'value'
    Yii::$app->request->setBodyParams($params);

Still not sure if you want or need to do this, but it is possible :)

jberculo
  • 1,084
  • 9
  • 27