best format to store php object to postgresql database - php

I wonder what is the best format to store PHP objects to database, an object have multiple parameters and methods, XML or binary or other formats?
for example :
$me = new Person();
$me->code= '007';
$me->name='antoine';
$me->store(); //this object is now stored into postgresql in Binary format or XML or ... you tell me !
//after few days :
$object = $database->retrievePersonByCode('007');
echo "my name is".$object->name;
How to do that ?

You will need to serialize it first. PHP has a serialize() function which you can use. But you should pay attention to this when using it:
Object's private members have the class name prepended to the member
name; protected members have a '*' prepended to the member name. These
prepended values have null bytes on either side.
Depending on the size of the object you wish to serialize you can use TEXT, MEDIUMTEXT or even LONGTEXT.

Personally I've standardized on json since any language can read it back easily. Plus it's human readable (not binary) and not nearly as verbose as XML. Since Postgres actually supports json as a data type, that is an additional bonus.

This question is the first stone of the existence of ORM and object oriented persistence layers.
Either you store PHP objects as is in a serialized way (text, json, xml, whatever...) and you loose the ability to perform queries on a particular attribute of your objects (ie looking for all Personn objects younger than 18 by example). Changing one atribute in your instance means updating the whole object.
Or you use a code layer that transposes your PHP objects to real tables or sets in the database. There is the ORM familly that uses abstraction layer (Doctrine, Propel and thousands more...) and there is the OMM familly that just uses Postgres (Pomm).

Related

Why does int value become string after reading from database?

In my Yii framework project, when I read data using Active Record from database whose column data type are all numerical, I got string type value using var_dump. I feel very confused.
Since php is a dynamically typed language, data types at interfaces often are kind of puzzling.
Usually when data is retrieved from the database, the driver doesn't bother to convert each value to the type in php which resembles the data type in mysql most (or you could also say, php isn't intelligent enough to do so automatically); you'd have to do that conversion yourself. Fortunately, it is really easy to do so:
$yourvar = (int)$yourvar;
Yii CActiveRecord creates model variables dynamically when we executes a query and by default they are of string type. They use _get & _set magic method to create dynamically, and they do not set their types so they are of string type.
As PHP is not strongly typed language so you should not worry about this, you can change their type.

Maintain XML Document state after session serialization

The class instance that I want to store in session holds an array of loaded DOMDocuments.
As noted in one of the answers here: PHP quirks and pitfalls, when you serialize an object containing XML, the XML structure does not survive the unserialize process. As I understand it PHP5 is supposed to automatically serialize session data, so what I need to know is how to make XML survive the serialize/unserialize process?
I've read about and it looks like it can't be done, plus the overhead involved in writing and reading the session file with the automatic serializing/deserializing seems to make it preferable to just read and write the XML files in the class instance on __sleep and __wakeup. Is that the case?
http://php.net/manual/en/function.serialize.php
This is useful for storing or passing PHP values around without losing their type and structure.`
The value to be serialized. serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. Circular references inside the array/object you are serializing will also be stored. Any other reference will be lost.
what is php resources
list of php resources
perhaps you can consider to store the original data into memcache, database,
while your session is pointing to that (like memcache key, database row ID)
additional read-up
you might felt amuse for the following (maybe i was wrong) -
http://www.php.net/manual/en/simplexml.resources.php
http://www.php.net/manual/en/dom.resources.php
http://www.php.net/manual/en/session.resources.php
Why don't you simply export the DOMDocument as a string, then serialize this string?

Is it possible to insert Object in a database?

Is it possible to insert Object in a database? (Asked in PHP interview.)
Yes, it is possible, using serialize().
But the answer hugely depends on context.
nobody suggested OR-mappers? interesting …
if you create your database tables so that they represent objects, you can use an object-relational mapper to store the values of your object members to the database.
for php there exists propel and many others
If you are talking about PHP object, it's not possible to insert an object into the database. To store it into the database you first need to serialize it and un-serialize it at the time of use.
That question is extremely vague and undefined. I mean, on one hand, you can serialize an object and insert it into the database. However, "inserting an object" depends on context. For example, is he referring to the fact that you can call an SQL statement like:
$a = new object();
// This makes no sense.
$sql = "Insert into table_name values($a);";
If that is what he's asking, then the answer is no, you can't do that unless you override the __toString() method which returns the values to be inserted into the database. Even then, the class isn't well defined, because you're saying that __toString() will be a database values, but yet that isn't clearly defined or implied without referring to the class object itself.
In any case though, if an Object represents database tables and so forth, then you want to separate each item based on responsibilities. For example, you can have object A which defines the database table, and then have a "manager" object B which inserts, updates, deletes, and select the item from the database. For example:
// NOT REAL PHP CODE....
class Table_Name
{
// Define primary keys, foreign keys, and attributes of the table.
private $column1;
public function setColumn1($value);
public function getCOlumn1();
}
class Table_Name_Manager
{
public function insert(Table_Name $obj);
public function delete(Table_Name $obj);
public function select(Table_Name $obj);
}
The above makes the most sense to me because it clearly defines the behaviors that you'd expect. You can simply use a manager to get items off the database, and modify the object, then you can call the manager again and insert, update, or delete.
yes you can, you just need to serialize it into an appropiate format.
The whole point of an open ended question such as that, is to find a way of doing what is being asked.
It should be noted that storing serialized objects into relational databases contradicts virtually all database normalization rules and can be considered very bad practice.
To store objects in a database you should use object relational mappers like Doctrine or Propel.
Serialized objects can be stored in your filesystem though. That's ok.
Short answer: no, it's not possible
Long answer: You cannot insert Object directly, you have to serialize it before storing, for example using built-in serialize() function or some custom XML serializer. Then you can put it in some TEXT or BLOB column.
Correct answer: To put objects in database, use some ORM (Object-Relational Mapping) tool. Most MVC frameworks have ORM built-in, most commonly utilizing Active Record pattern.
You can also be a wise-ass:
You: "You could take the PHP object from memory and port it to either Java or .NET and then use a Versant object database to store the object."

Is marshaling/ serialization in PHP as simple as serialize($var)?

here's a definition of marshaling from Wikipedia:
In computer science, marshalling
(similar to serialization) is the
process of transforming the memory
representation of an object to a data
format suitable for storage or
transmission. It is typically used
when data must be moved between
different parts of a computer program
or from one program to another.
I have always done data serialization in php via its serialize function, usually on objects or arrays. But how is wikipedia's definition of marshaling/serialization takes place in this serizalize() function?
What serialize doesn't do is transport class definitions. When unserializing an object, that object's class definition must be present (loaded from the code base), otherwise unserializing will fail. From the Wikipedia article you mention:
To "marshal" an object means to record its state and codebase(s) in such a way that when the marshalled object is "unmarshalled", a copy of the original object is obtained, possibly by automatically loading the class definitions of the object. You can marshal any object that is serializable or remote. Marshalling is like serialization, except marshalling also records codebases. Marshalling is different from serialization in that marshalling treats remote objects specially.
If I understand correctly, Serialize is definitely not 100% compatible with the definition of marshaling in that respect. I don't know a pre-defined mechanism that would do this in PHP. I guess you would have to combine the serialized data and all necessary class definitions into a package (a ZIP file for example).
Like Pekka mentioned above, PHP doesn't include the class definition, so it does not do marshaling. If the class for a serialized object is present, however, then the answer to your question is yes: serialization is as easy as serialize($abc).
The best way that I know of to take care of marshaling in PHP is to use a third party tool like Google Buffer Protocols or Facebook (Apache?) Thrift, which will serialize and marshal for you. Kind of a roundabout way of doing it (and as long as you have the class present, you don't need to marshal anyway), but they're probably the best solution to the problem.

fetching an Integer from DB using Zend Framework returns the value as a string

When I run an sql query using the ZF wrappers, all the numeric values return as strings.
What do I need to change so the values will return in the same data type as they are in the DB?
I implemented a lot of the Zend_Db code in Zend Framework.
As other have stated, the reason that Zend_Db returns strings instead of native PHP integers or floats is that PHP's database extensions return strings. And the reason for that is that there might be no native PHP type to represent certain database type.
For example, MySQL's BIGINT is a 64-bit signed integer. By default, the PHP int type is limited to 32-bit values, so if you fetch data from the database and implicitly convert it to int, some values might be truncated. There are several other similar cases, for float and dates, etc.
Using the string representation for all data types is the best way to remain simple and consistent, be safe about avoiding data loss, and avoid writing lots of vendor-specific special-case code to do data type mapping. That extra code would incur a performance penalty, too.
So if you have specific cases where you need database results to be mapped to native PHP data types, you should implement it yourself in your application code (e.g. in a custom Zend_Db_Table_Row class).
Databases typically return result sets as text. Unless your db adaptor converts things for you (and to sounds like yours does not), all values will come back as strings--dates, enums, etc. as well as integers.
If you are dealing with a small number of tables with only a few integer fields, just hand convert them. If you are dealing with a slightly more complex situation, you could iterate through the columns using the database definitions (see sqlite_fetch_column_types(), etc.). If your situation is more complex than seems reasonable for these solutions, consider switching to a more featureful framework.
It appears as if this has been requested in the past but has not yet been implemented. #ZF-300 was last commented on on 9 Jan 09.
Maybe you could share why you are wanting to perform the typecasting and we could help you out another way? PHP is pretty lenient when it comes to variable datatypes...
For an example of using a custom Zend_Db_Table_Row to get correct data types, as Bill Karwin suggested, have a look at the class here: http://www.zfsnippets.com/snippets/view/id/70
It can be implemented in your model as:
class YourTableName extends Zend_Db_Table_Abstract
{
protected $_name = 'your_table_name';
protected $_rowClass = 'Model_Row_Abstract';
}
You may want to change Model_Row_Abstract's datatype for tinyint to bool if you use it strictly to hold boolean values.

Categories