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..
Related
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.
I have a built an MVC application with a model layer containing entities, data mappers and service classes. So far so good. But now I have a controller that need to show a report containing data from multiple db tables with no relation to any entities in my model. The report is built from a advanced MySQL query containing joins, SUM/AVG-selects. All I want is an array of the data so be shown in the VIEW.
Can I mix methods in my service layer, some that returns entities ("getById()") and some that just returns array of data from my database query ("getAdvancedReport()")?
Is it OK to put the db-queries right in the service layer? If not, where should they go? The data mapper feel wrong because its job is just to map my entites to the db, not to retrieve custom data.
Maybe just "Coding bureaucracy" but i need to do this right.
Cant find anything on the net other than simple CRUD examples of the domain model.
Not really an answer .. more like pontifications with bottle of beer
You seem a bit confused about the point in having data mappers and even about domain object in general.
Data mappers are responsible for the information exchange between storage (which sometimes is an SQL database) and domain object. If you have even a bit normalized DB structure, the database entities and domain objects will not map 1:1. Mappers are made for specific domain object , not for the database tables. A single domain object can even have multiple mappers (for example: one mapper which stores data in DB, and one in session).
If your Report object has no domain logic, you can even use an active record. The pragmatic approach is to use them when the potential domain object has only CRUD with no domain logic. If there is some computation, stick with domain object + data mapper pair.
Service layer is for application logic, not storage logic. There should be no SQL in it. Service should mostly be governing the interaction between undetermined mix of domain objects and mappers. With the exception of mailing services and similar structures.
Also, usually on-line reports are dynamic. You can order the data, filter it and otherwise manipulate. You would end up with a service, which can manipulate the Report object, apply filter to it or extract data from said object. All this tinkering is "application logic".
that's it ... I run out of beer
Can I mix methods in my service layer, some that returns entities ("getById()") and some that just returns array of data from my database query ("getAdvancedReport()")?
Yes, but I would correct your sentence as such: some that returns entities and some that just returns array of data
=> the user of the service doesn't care where the entity/data comes from. So, yes your service can return entities and raw data (array of primitive types).
Is it OK to put the db-queries right in the service layer?
No
If not, where should they go?
In the Repository/DAO. It is OK to perform native queries in the Repository. And the Data Mappers are not used here, simply because we don't need to map entities.
To sum up:
Service->getMyData() > Repository->getMyData() > DB query
Is it OK to put the db-queries right in the service layer? If not,
where should they go?
DB queries should be always placed in data-mapper, because "Service" shouldn't know, where are data from.
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.
Now that I have read an awfull lot of posts, articles, questions and answers on OOP, MVC and design patterns, I still have questions on what is the best way to build what i want to build.
My little framework is build in an MVC fashion. It uses smarty as the viewer and I have a class set up as the controller that is called from the url.
Now where I think I get lost is in the model part. I might be mixing models and classes/objects to much (or to little).
Anyway an example. When the aim is to get a list of users that reside in my database:
the application is called by e.g. "users/list" The controller then runs the function list, that opens an instance of a class "user" and requests that class to retrieve a list from the table. once returned to the controller, the controller pushes it to the viewer by assigning the result set (an array) to the template and setting the template.
The user would then click on a line in the table that would tell the controler to start "user/edit" for example - which would in return create a form and fill that with the user data for me to edit.
so far so good.
right now i have all of that combined in one user class - so that class would have a function create, getMeAListOfUsers, update etc and properties like hairType and noseSize.
But proper oop design would want me to seperate "user" (with properties like, login name, big nose, curly hair) from "getme a list of users" what would feel more like a "user manager class".
If I would implement a user manager class, how should that look like then? should it be an object (can't really compare it to a real world thing) or should it be an class with just public functions so that it more or less looks like a set of functions.
Should it return an array of found records (like: array([0]=>array("firstname"=>"dirk", "lastname"=>"diggler")) or should it return an array of objects.
All of that is still a bit confusing to me, and I wonder if anyone can give me a little insight on how to do approach this the best way.
The level of abstraction you need for your processing and data (Business Logic) depends on your needs. For example for an application with Transaction Scripts (which probably is the case with your design), the class you describe that fetches and updates the data from the database sounds valid to me.
You can generalize things a bit more by using a Table Data Gateway, Row Data Gateway or Active Record even.
If you get the feeling that you then duplicate a lot of code in your transaction scripts, you might want to create your own Domain Model with a Data Mapper. However, I would not just blindly do this from the beginning because this needs much more code to get started. Also it's not wise to write a Data Mapper on your own but to use an existing component for that. Doctrine is such a component in PHP.
Another existing ORM (Object Relational Mapper) component is Propel which provides Active Records.
If you're just looking for a quick way to query your database, you might find NotORM inspiring.
You can find the Patterns listed in italics in
http://martinfowler.com/eaaCatalog/index.html
which lists all patterns in the book Patterns of Enterprise Application Architecture.
I'm not an expert at this but have recently done pretty much exactly the same thing. The way I set it up is that I have one class for several rows (Users) and one class for one row (User). The "several rows class" is basically just a collection of (static) functions and they are used to retrieve row(s) from a table, like so:
$fiveLatestUsers = Users::getByDate(5);
And that returns an array of User objects. Each User object then has methods for retrieving the fields in the table (like $user->getUsername() or $user->getEmail() etc). I used to just return an associative array but then you run into occasions where you want to modify the data before it is returned and that's where having a class with methods for each field makes a lot of sense.
Edit: The User object also have methods for updating and deleting the current row;
$user->setUsername('Gandalf');
$user->save();
$user->delete();
Another alternative to Doctrine and Propel is PHP Activerecords.
Doctrine and Propel are really mighty beasts. If you are doing a smaller project, I think you are better off with something lighter.
Also, when talking about third-party solutions there are a lot of MVC frameworks for PHP like: Kohana, Codeigniter, CakePHP, Zend (of course)...
All of them have their own ORM implementations, usually lighter alternatives.
For Kohana framework there is also Auto modeler which is supposedly very lightweight.
Personally I'm using Doctrine, but its a huge project. If I was doing something smaller I'd sooner go with a lighter alternative.
Can you, please, explain me the differences between the following database representatives, say, in PHP.:
ORM
DAO
DataMapper
ActiveRecord
TableGateway
Any examples would be appreciated.
That would require a pretty long answer. Instead of repeating what others have said better and in more detail before me, I link you to some relevant pages. I suggest to look through them. Maybe follow a few additional links. Wikipedia is always a good start. If you still have any questions about one or the other pattern after going through the links, feel free to come back to SO and ask again. But if you do, try to narrow it down. It's better to ask multiple questions and focus on particular aspects than expecting people to write an essay for you.
Object Relational Mapper
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 relational databases and object-oriented programming languages.
Data Access Object
Use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data.
DataMapper
A layer of Mappers (473) that moves data between objects and a database while keeping them independent of each other and the mapper itself.
Active Record
An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.
Table Data Gateway
An object that acts as a Gateway (466) to a database table. One instance handles all the rows in the table.