Thoughts on data persist in Symfony 2

Hi All,

Today I will be discussing about persisting form submitted data in Symfony 2. Data persisting is all about inserting/updating records to/in a table in database. In this example I assume that you have a form ready which will contain few fields in order to insert values to the database. This is exactly what I am going to do in the following scenario. I will have a table (Entity) called ‘user_details (UserDetails)’. I will be passing some values from a form (which is not here) to the ‘insertUserDetails‘ action in ‘UserDetails‘ controller. Then using that action, I will be inserting new user details to the ‘user_details‘ table.

Well, in this post I would like to have an open ended discussion regarding data persisting. The approach you are using can be different from mine but still do the same intended job. More or less performance can vary, lines of codes can vary, efficiency can vary and so on.  You can see the controller and function below. First take a look at the code and I will explain the code below.

<div>namespace ACME\TestBundle\Controller;</div>
<div>use Symfony\Bundle\FrameworkBundle\Controller\Controller;</div>
<div>use Symfony\Component\HttpFoundation\Request;</div>
<div>class UserDetailsController extends Controller</div>
<div>    public function userDetailsAction(Request $request)</div>
<div>    {</div>
<div>    $message = '';</div>
<div>    $em = $this-&gt;getDoctrine()-&gt;getManager();</div>
<div>        try{</div>
<div>            $em-&gt;getConnection()-&gt;beginTransaction();</div>
<div>            $postData = $request-&gt;request-&gt;get('acme_test_user');</div>
<div>            $userD = new ACMETestBundle\Entity\UserDetails();</div>
<div>            $userD-&gt;setUserName($postData['username']);</div>
<div>            $userD-&gt;setPassword(md5($postData['password']));</div>
<div>            $userD-&gt;setActive($postData['isActive']);</div>
<div>            $userD-&gt;setEnabled($postData['isEnable']);</div>
<div>            $em-&gt;persist($userD);</div>
<div>            $em-&gt;flush();</div>
<div>            $em-&gt;getConnection()-&gt;commit();</div>
<div>            $message = 'Success!';</div>
<div>        }catch(\Exception $ex){</div>
<div>            $em-&gt;getConnection()-&gt;rollback();</div>
<div>            $message = 'Failed -  '. $ex-&gt;getMessage();</div>
<div>        }</div>
<div>    $em-&gt;close();</div>
<div>    return $message;</div>
<div>    }</div>

And here is my walkthrough regarding the code,

  • In userDetailsAction, I will be passing a  ‘Symfony\Component\HttpFoundation\Request‘  parameter. Because we access this Request in order to access form submitted values.
  • I will be declaring a blank variable called ‘$message‘ to be filled and returned with a relevant error or success message.
  • Instantiating the doctrine manager and and assigning to a variable called ‘$em‘.
  • Surrounding the rest of the code with a standard try/catch block for two reasons. One is to capture exceptions and provide a meaningful message back to the user. And the second one is to halt the process and revert (rollback) any transactions. I believe this is really a safe and helpful approach. Imagine some problem occurred during the insertion of some value. If we didn’t rollback, everything else may get inserted to the table up to the point where failure happened. By issuing rollback command we ensure that nothing will get inserted if any problem occurred during the transaction. One of the major reason to surround the whole transaction using try/catch block and issue rollback inside the catch.
  • First thing we do inside the try block is to start the transaction. I think that’s obvious and needs no explanations.
  • After the transaction has started I am accessing the post submitted data via ‘$request‘ object.  For your information ‘acme_test_user‘ is the name of the form (in other words, the string returned by the getName() function in the form class).
  • Next what I do is setting the data one by one, using the variable ‘UserD‘, which is an object of ‘UserDetails‘. After setting all (mandatory) values I persist the data set object and flush it.
  • Finally, I commit the whole transaction, where the actual insert happens in the ‘user_details‘ table.

Well that’s pretty much it for today. As I mentioned at the beginning of the post, this post is much like an open ended discussion, which helps you to compare your data persisting approach with mine. Feel free to place your suggestions and comments in the comments section below.

Cheers 🙂



3 thoughts on “Thoughts on data persist in Symfony 2

Leave a Reply

Your email address will not be published. Required fields are marked *