SQL Class Data Type - php

Is it possible to make the data type of a column in a table an object of a class?
For instance, if I have a class that manages strings called "MyString", is it possible to use it instead of varchar?

No, you cannot. That's why we have ORM : Object Relational Mapping
Quoting Wikipedia :
Object-relational mapping (ORM, O/RM, and O/R mapping) in computer
software is a programming technique for converting data between
incompatible type systems in object-oriented programming languages.
This creates, in effect, a "virtual object database"
I think that's what you were looking for, good luck !
For good ORMs libraries in PHP, look at this : Good PHP ORM Library? on S.O

No, databases are separate entities to scripting languages, so a database like MySQL has no concept of a PHP Class.... and PHP Classes are different to (for example) Java classes, so to implement this, every database would need a datatype for every conceivable class-based language.... and then consider the practicalities of a PHP script wanting to access data stored by a Java app.
What you can do, however, is serialize objects, and store them in a database table column, of type VARCHAR... but beware that private/protected methods serialise with NULL characters in the serialized string

If you weren't using MYSQL probably you could use User-Defined Datatypes.
But since they are not available for MYSQL, you only can use this Datatypes.

Related

Why should we fetch in object?

I'm not referring to a particular database driver or so but we, as PHP developer, have always had the choice to use either arrays or object as return type of a database query.
So for example we could access the column "title" with either $array['title'] or $object->title.
For example mysql PHP built-in functions mysql_fetch_assoc() and mysql_fetch_object() give this choice.
I noticed that the object-way (as I'm gonna call it) is much worse:
You cannot specify table names that contains special chars such as . or - and use them with objects.
Object are usually heavier than arrays
Object doesn't have all the cool functions to manage them as arrays do
Arrays better explain the table structure rather then property chaining.
There are few other little things about object vs array war regarding database results but these are the main ones.
Why do people even take the object-way as choice?
You can specify table names that contains special chars such as . or -
Object are more flexible than arrays
Object have all the cool functions that you can imagine to manage them, you just have to write a few of them
Arrays don't cleanly express relationships between tables, object mapping does.
I mostly use it because $user->name is a lot easier on the eyes than $user['name']

Data Mapper Design Pattern and Gateways - Newbie question

Please, correct me if I'm wrong:
If we use a Dao/Vo pattern or a TDG pattern we will have a nice code organization by having for each (or at least for a lot of) tables a related class.
The problem with this approach is that or data IS NOT closed inside a given table. We have some domain specific data, like findDogBreed(); or findBookBestSellerAuthor(); and the above patterns don't seem to deal with this nicely.
Once solution is to use Mappers. Mappers will contain a set of methods and properties related to one table BUT they will not be closed to that table only nor will they be related to a specific SQL Schema.
The problem is, if we start to abstract all those things, we will NOT have access to SQL syntax. What if we need our database administrator to work on it ? And on more complex queries, using mappers could lead to a really messy abstraction "thing".
Is this correct ? If so, I'm wondering what paths do we have in order to find a middle term here.
You don't have to lose the option to write SQL manually when you abstract the functionality, even on multiple levels abstraction.
E.g. look at Doctrine, which is Hibernate-inspired ORM for PHP. It allows you to write queries in DQL (Doctrine Query Language) that translates to SQL and automatically maps your entities, but you can also write native SQL (most often for performance optimization), but you need to define the result mapping by yourself.

What is an ORM in a web application?

I recently got a reply from a server company asking if we are using an ORM in our application which does all the work of sifting application side (like Rails) or if we write reams of SQL, embedded functions etc which would make the database server do the processing for you.
Can anyone explain what is meant by this. Our web application is made up of PHP scripts with functions that make calls to the database to retrieve rows of data, then PHP processes these rows as needed to return results to the user.
thanks
It basically makes your database tables appear like objects on the PHP side of your site so you can easily manipulate data.
For example if you have a User table, getting this user's name is as easy as doing: $myUser->getName();
adding a new user in your database would be:
$myUser = new User();
$myUser->setName('John Doe');
$myUser->save();
Of course this is pseudo code (actually PHP Symfony/Doctrine code), but it's a simple example so you get the point.
An ORM is an abstraction that is supposed to simplify working with a relational database in an object oriented language. It's basically a set of classes and methods that let you create, retrieve and update data without using SQL directly.
For instance instead of writing
$result=mysql_query('select * from sandwiches where color='green' and size='2');
you can use an interface like
$result=$sandwiches->get('color'=>'green',=>'size'=>'2');
and the ORM turns this into SQL and executes the query, taking care of joins, etc.
Popular PHP ORMs are Doctrine and Propel
If you don't know whether you're using one, than it's pretty unlikely that you are!
It is an Object Relational Mapping. See link to wikipedia below.
http://en.wikipedia.org/wiki/Object-relational_mapping
ORM is Object Relational Mapper. which maps the java objects to the database tables and lets you perform some database transactions thorough your code.
EX of ORM tools are like Hibernate, Ibatis ..
ORM is used for Mapping your database objects to your application objects.
In a simple application using ORM, you should have functions that gets/sets data from/to DB should return appropriate application object/objects.
ORM is a Wikipedia article on Object Relational mapping.
Object Relational Mapping is an easy way of mapping Database objects ( tables, views ... ) to classes/objects in OOPL.
Hibernate and NHibernate are a few examples of ORM. it does all the tedious task of handling and mapping result sets..

Ruby equivalent to PHP's "unserialize" function?

I'm working with some serialized data from a MySQL database and I need to deserialize this using Ruby (the serialized data is used to build up a WHERE clause for a database query). PHP has the unserialize() method which will convert it into an Array; what is the Ruby equivalent of this?
The data in question looks like this, if it helps any:
a:2:{s:5:"Lists";a:1:{i:0;s:2:"11";}s:5:"Rules";a:1:{i:0;a:3:{s:4:"type";s:5:"group";s:9:"connector";s:3:"and";s:5:"rules";a:1:{i:0;a:3:{s:4:"type";s:4:"rule";s:9:"connector";s:3:"and";s:5:"rules";a:3:{s:8:"ruleName";s:2:"21";s:12:"ruleOperator";s:10:"isnotempty";s:10:"ruleValues";a:1:{i:0;s:0:"";}}}}}}}
I guess the exact equivalent would be this. You could also check out Ruby's Marshall Class, specifically Marshal.load.
Look at Ruby's Marshal Class.
From the docs:
The marshaling library converts
collections of Ruby objects into a
byte stream, allowing them to be
stored outside the currently active
script. This data may subsequently be
read and the original objects
reconstituted. Marshaled data has
major and minor version numbers stored
along with the object information.
Of course this is a two way street, you can only un-Marshal, Marshaled ruby objects.
If it's XML, there's the Hash.from_xml method.

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