Storing instances of class having inner-classes into a mySQL database - php

I have a PHP class which will have at least two inner-classes. I want to store the instances of this class into a mySQL database so that I can get all the data in a bulk instead of going through multiple number of tables.
So far, I have looked up serializing in PHP and storing them into a BLOB field of the database. However, with a object-class having inner-object-classes I am not sure how it will turn out or even is it possible at all? I could not find any helpful resources on this topic specifically.

What you are looking for is ORM, since serializing an object and storing in a database is almost never the solution. This is a nice thread for ORM benefits and their intricacies.
ORM allows you to map specific parts of an objects to difference fields, using multiple tables, all the way down to its most basic structures. It can handle one-to-many and many-to-many relationships, and perform operations on creation that give you more creative freedom and elegance in your code.
It is much faster than storing a serialized object because there are smaller more optimized queries performed.
The main advantages of ORM are:
Ability to use class inheritance
Built in validation for data structure security and efficiency
Prebuilt queries and methods on objects.
Disadvantages of ORM:
Boilerplate to set up.
More abstract than serializing an object.

Related

how to store newly created objects and read its info on demand

I have a form that a user will enter their studentID,Name,Major etc. then use those info to fill up 'student' class to create a 'student' object.
Now, I want to store these objects somewhere, somehow, and I want to be able to pull them back to use its data. I've looked into 'object serialization' but not quite sure if this will fulfill my needs, as I don't fully understand how this thing works...any help would be great, thanks.
And, I don't want to create a database, at all. No Mysql is allowed for this little assignment of mine...
You could serialize your object as is and persist it to disk, but what happens if you want to search for students based on some criteria?
Usually, a relational database is used and an ORM to map your PHP objects to a rdbms table
Wikipedia has a list of ORM's and frameworks for PHP, If you want something more lightweight then managin a db server, at least look into Sqlite
Be careful when storing serialize objects. You might loose the ability to do certain things like search records. And if you don't understand how they work then they might behave unexpectedly.
A better approach would be to store individual properties as rows in database tables and then fetch the data into objects. To do this you can use ORMs like Doctrine which will map objects to database tables and persist them. Or a simple database class using PDO should fulfill your basic needs as well.

in Zend, Why do We use DB Model class and Mapper class as two separate?

I am working on the zend project, I am referring on other zend project to create the new Zend Project.But I don't like to blindly follow that project without understanding. In the Zend Directory structure, In Model class there are mainly two type of classes I see, like as in
- models
- DbTables
- Blog.php //Extends Zend_Db_Table_Abstract
- Blog.php // Contains methods like validate() and save()
- BlogMapper.php // Also Contains methods like validate(Blog b) & save(Blog b)
Why this specific structure is followed?
Is this is to separate Object class and Database model class?
Please explain.
DataMapper is a design pattern from Patterns of Enterprise Application Architecture.
The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn't know even that there's a database present; they need no SQL interface code, and certainly no knowledge of the database schema.
How you store data in a relational database is usually different from how you would structure objects in memory. For instance, an object will have an array with other objects, while in a database, your table will have a foreign key to another table instead. Because of the object-relational impedance mismatch, you use a mediating layer between the domain object and the database. This way, you can evolve both without affecting the other.
Separating the Mapping responsibility in its own layer is also more closely following the Single Responsibility Principle. Your objects dont need to know about the DB logic and vice versa. This gives you greater flexibility when writing your code.
When you dont want to use a Domain Model, you usually dont need DataMapper. If your database tables are simple, you might be better off with a TableModule and TableDataGateway or even just ActiveRecord.
For various other patterns see my answer to
ORM/DAO/DataMapper/ActiveRecord/TableGateway differences? and
http://martinfowler.com/eaaCatalog/index.html
The idea of a Model is to wrap up the logical collection of data inside of your code.
The idea of a DataMapper is to relate this application-level collection of data with how you are storing it.
For a lot of ActiveRecord implementations, the framework does not provide this separation of intent and this can lead to problems. For example, a BlogPost model can wrap up the basic information of a blog post like
title
author
body
date_posted
But maybe you also want to have it contain something like:
number_of_reads
number_of_likes
Now you could store all of this data in a single MySQL table to begin with, but as your blog grows and you become super famous, you find out that your statistics data is taking an awful lot of hits and you want to move it off to a separate database server.
How would you go about migrating those fields of the BlogPost objects off to a different data store without changing your application code?
With the DataMapper, you can modify the way the object is saved to the database(s) and the way it is loaded from the database(s). This lets you tweak the storage mechanism without having to change the actual collection of information that your application relies on.

own ORM: database records in case of JOIN?

We are doing our own framework with ORM capability. The database tables are classes now, but how about records? Lets imagine two tables:
Users
ID,USERNAME
Emails
USER_ID,ADDRESS
so, a record object will have getID(), getUSERNAME() methods, etc but if the two tables are JOIN-ed, it cant have two types right? Since there is no multiple inheritance. And what about field collision?
DBIx::Class handles this by having a Class for each table, and joins are represented by a method that gets an object matching the other table..
$myAddress = $myUser->emails->address;
I think every class should represent a record and a whole table should be an array (or some other collection) of objects. Take a look at http://www.doctrine-project.org/ to get some ideas.
And for JOIN, you should have some mechanism for defining aliases. That way, you can deal with field collision.
And for getters and setters, you can use __call, __get and __set. See http://php.net/manual/en/language.oop5.overloading.php for more info.
I'm providing some insight based on the Model/ORM implementation of this PHP UI Framework . Here are some suggestions from me:
Don't decide blindly to map functions into fields. Why not use get('field') and set('field'). There is no downside (apart from lack of IDEs hinting), but you can avoid code generation or catch-all which usually is slower.
When joining you wouldn't necessarily want multiple objects. In my ORM a single Model can work with joined tables. This introduces transparency and when you call $model->set('address') it might be associated with joined table. Im still using sub-instance of a dynamic query for sub-selects but for joins there is no need.
I've see a lot of power of inheritance and ability to re-shape parent models in parent model. Each table can have multiple models depending on your business uses.
Models and ORM should be separated but should play together very closely. I've also managed to make everything play well with generic views and generic controllers, which is a great time-saver.
Hopefully this would help find your own way or to decide on not implementing your own ORM. It's not an easy task.

Does every single table in Zend have to map to its own Class?

I am not suggesting that all models are tables.
What I am asking is whether every single table must also have its own class defined specifically for it when using Zend? Is there any way of getting away from this awkward boiler-plate coding. We're just starting to look into Zend (hoping to leave procedural PHP land!) and my colleague thinks this could end up being pretty time-consuming.
Is this the reason for people using ORM solutions? Is there any other way around this?
Thanks for your replies.
The Zend Table classes follow the Table Data Gateway pattern, which by definition
... holds all the SQL for accessing a single table or view: selects, inserts, updates, and deletes. Other code calls its methods for all interaction with the database.
In the book, Fowler is not that rigid about that, saying that
for very simple cases, you can have a single TDG that handles all methods for all tables. You can even have one for views or even for interesting queries that aren't kept in the database as views.
However, except for being able to use Views, Zend_Db_Table does not accomodate for this. You can create queries to multiple tables, but those would have to be made through the Zend_Db_Adapter directly or - when using joins - by switching off the integrity check. Otherwise, you have to use the API offered by Zend_Db_Table Relationships
So yes, one instance should correspond to one table or view. You do not need to create classes for that though if you dont plan on extending the classes. Zend_Db_Table_Definitions allow you to configure Zend_Db_Table instances on the fly.
Note that TDG is a DataSource Architectural Pattern and not an Object-Relational pattern. It's purpose is not to help with impedance-mismatch, but with separating database access code from business logic.

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..

Categories