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 used only Mysql and all the parameters coming from the client allowed themselves to receive data from the database without any problems.

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

    But the point 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, so you cannot find a record using the condition id == '1' if id in mongodb is a number.



    In order not to complicate or increase the amount of code by adding (int) to cast
    request->getParam('id', 0);
    ?>
    


    The following solution was chosen - creating your own request manager based on the standard CHttpRequest.
    The next class
    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 registered in the settings
    	'request' => array(
    		'class' => 'CParseRequest'
    	),
    


    Now the received data will always be cast to the desired type. If an array of any nesting comes to us, then all its elements will also be converted to the necessary types.

    We do not have situations when the number needs to be transmitted as a string, therefore this solution completely covered the needs of the project.

    It will be interesting to hear other people's opinions on how they solved this problem.

    upd. made a change indicated by VolCh

    Also popular now: