Zend Framework Source Code Snippets

Zend_Db_Table_Row datatype conversion support

Bookmark and Share
1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
<?php
class Model_Row_Abstract extends Zend_Db_Table_Row {
        
        protected $_dataTypes = array(
                'bit' => 'int',                'tinyint' => 'int',
                'bool' => 'bool',
                'boolean' => 'bool',
                'smallint' => 'int',
                'mediumint' => 'int',                'int' => 'int',
                'integer' => 'int',
                'bigint' => 'float',
                'serial' => 'int',
                'float' => 'float',                'real' => 'float',
                'numeric' => 'float',
                'money' => 'float',
                'double' => 'float',
                'double precision' => 'float',                'decimal' => 'float',
                'dec' => 'float',
                'fixed' => 'float',
                'year' => 'int'
        );        
        /**
         * Initialize object
         *
         * Called from {@link __construct()} as final step of object instantiation.         *
         * @return void
         */
        public function init() {
                $table = $this->getTable();                if ($table) {
                        $cols = $table->info(Zend_Db_Table_Abstract::METADATA);
                        foreach ($cols as $name => $col) {
                                $dataType = strtolower($col['DATA_TYPE']);
                                if (array_key_exists($dataType, $this->_dataTypes)) {                                        settype($this->_data[$name], $this->_dataTypes[$dataType]);
                                }
                        }
                }
        }}
?>

Comments

darh darh
9 months ago

FYI:

PostgreSQL ZF adapter (without your patch), PDO and "native" returns:

var_dump($db->fetchRow('SELECT 8::int, 8::real, true, false'));

Will return
array(3) {
["int4"]=>
int(8)
["float4"]=>
string(1) "8"
["bool"]=>
bool(false)
}

You must login before commenting on a snippet. If you do not have an account, please register.

Snippet description

As we know, all DB adapters return all data as strings, so this small extension gets datatype from table description and converts necessary fields to php datatypes like int, bool or float. Enjoy!

Snippet details

Created:
Stalin Stalin
9 months ago
Edited:
Stalin Stalin
9 months ago
Revision Id:
130
Edit Message:
Added PostgreSQL numeric types
ZF Version
1.8.3
Tags:
db datatypes Zend_Db_Table_Row
Comments:
1
Views:
377
Points:
2 (2 votes)

History

r130

Added PostgreSQL numeric types

Stalin Stalin
9 months ago
diff
r129

Initial Release

Stalin Stalin
9 months ago