Question

I have created a little project where I pass data from my controllers to a service class which uses an ORM to for example save an object:

Something like this: The UserController receives the post data and passes it to the UserService. The UserService creates a user object and saves it to the database with $user.save();

Now I'm struggling with two things:

First: Let's say I use a repository to add the user, it would be like this: Controller passes post data to the service which creates the user object and passes it to the repository. The only thing the repository has to do is call $user.save(), isn't that a bit weird? Why not calling save in my service, because using a repository just to call a save method seems overkill to me.

Second: I read that when you use repositories, you can easily change storage methods because your application isn't aware which one is used. But before passing an object to your repository, you have to create it. Using an ORM, each one has a different way: Doctrine uses $user = new User while Propel uses $user = new User(), idiorm uses $user = ORM::for_table('user')->create(); So when switching to another ORM for some reason comes with changing this in your project too, no?

Was it helpful?

Solution

First: Have a read about the responsibilities of Model View and Controller. There's a reasonable explanation with an example at this site: http://tomdalling.com/blog/software-design/model-view-controller-explained/

With regard to the Model and your ORM - the ORM would probably exist within the Model. So you should be asking your Model to create a new object (which may represent a single table or a series of related tables - your Model should understand these relationships). You can then pass data to your Model and your Model should then store the data into the appropriate columns in the appropriate tables. A simple example, imagine creating an object called 'Family' where you might specify 2 parent names, a variable number of children names and then tell the Model to save this. The Model may take this 'Family' object and create a single Family table record and 5 Person table records, flagging some as parents and others as children.

Second: The 'Storage Methods' referred to are (in my opinion) referring to the database you use. For example I know that Propel supports MySQL, PostgreSql, MSQL, Oracle, and others. My switch the configuration to a different database Propel will automatically start talking the appropriate language for the new database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top