📜 ⬆️ ⬇️

Type casting in Yii :: app () -> request

Hello!

I want to share with you a small solution to the problem that I encountered when transferring part of the project data to mongodb.
Initially, we only used Mysql and all the parameters coming from the client allowed itself to receive data from the database without any problems.

<?php $id = Yii::app()->request->getParam('id', 0); $data = Data::getForId($id); ?> 

And the bottom line is that for mysql there is no difference [select * from data where id = 1] or [select * from data where id = ' 1 ' ].
But mongodb distinguishes data types, therefore it is impossible to find a record using the condition id == '1' if id in mongodb is a number.
')


In order not to complicate and not increase the amount of code by adding (int) to bring the type
 <?php $id = (int)Yii::app()->request->getParam('id', 0); ?> 


The following solution was chosen - creating your own request manager based on the standard CHttpRequest.
It turned out the next class
 <?php class CParseRequest extends CHttpRequest { public function getParam($name,$defaultValue=null) { $data = parent::getParam($name, $defaultValue); $this->parseData($data); return $data; } public function getQuery($name,$defaultValue=null) { $data = parent::getQuery($name, $defaultValue); $this->parseData($data); return $data; } public function getPost($name,$defaultValue=null) { $data = parent::getPost($name, $defaultValue); $this->parseData($data); return $data; } /** *     */ protected function parseData(&$data) { if (is_array($data)) { foreach ($data as &$prop) { $this->parseData($prop); } } else { if (preg_match("/^[\d]+$/", $data)) $data = (int)$data; } } } 


The following module should be specified in the settings.
  'request' => array( 'class' => 'CParseRequest' ), 


Now the data will always be brought to the desired type. If we receive an array of any nesting, then all its elements will also be reduced to the necessary types.

We do not have situations when the number needs to be passed as a string, so this solution fully covered the needs of the project.

It will be interesting to hear the opinions of other people about how they solved this problem.

upd. Modified the specified VolCh

Source: https://habr.com/ru/post/149739/


All Articles