• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Database / Basics On Doctrine CRUD Operations

Basics On Doctrine CRUD Operations

July 18, 2012 by Rana Ahsan 3 Comments

Dctrine ORM

Some developers don’t start using doctrine in their application just because they find it a little difficult to get started(I listened so from some of my own friends too). And unluckily, I also faced some similar issues as well. I tried to start it at a very early time when I was new in LAMP(Linux, Apache, MySQL And PHP Environment) and found it a little difficult to understand the official documentation for installation and get started smoothly. I had to take the help of several online tutorials as well. In an earlier post, I have already discussed the basic usage and integration of Doctrine ORM with Codeigniter framework. Today, in this tutorial, I am going to give some PHP code examples and show how we can perform the doctrine CRUD operations.

Important Note: I will be using same contact entity used on the earlier tutorial. So, if you haven’t read the previous tutorial, at least get an idea of the entity structure from there.

Select/Read Operation:

To select a single entity by its identifier: This is a common need, and thus doctrine made the work easy for us with its integrated function. You can pass the entity name and the identifier value to the “find” function of the Doctrine entity manager, and it will return you a single entity object. The code is as follows:


function get_single($id)
    {
        try
        {
            $city = $this->em->find("PdContact",$id);
            return $city;
        }
        catch(Exception $err)
        {
            return NULL;
        }
    }
Code language: PHP (php)

Another thing, that needs to be remembered here is that the identifier value must be the value of the primary key column. Suppose you have two columns in your database table named ‘id’ and ’email’, and you made the ’email’ column as the primary key(you maybe used the ‘id’ for auto increment). In this case, Doctrine will search for the entity via the email column in a database table with the given identifier value, not the id column.

To record in a specified range and with/without constraint: This is often required in cases where data are shown on a data grid and have a paging-like system to show only a certain number of data. You may have some conditions as well, like retrieving only active members, approved messages, joining more than one table etc. The example code for such cases is as follows:


 /**
     * Return list of records according to given start index and length
     * @param Int $start the start index number for the result entity list
     * @param Int $length Determines how many records to fetch
     * @param Array $criteria specify where conditions
     * @param String $orderby specify columns, in which data should be ordered
     * @return type
     */
    function get_by_range($start=0,$length=10,$criteria = NULL,$orderby=NULL)
    {
        try
        {
            return $this->em->getRepository("PdContact")->findBy($criteria, $orderby, $length, $start);
        }
        catch(Exception $err)
        {
            return NULL;
        }
    }
Code language: PHP (php)

Retrieve total row count for an entity in database: I didn’t find any built-in function for this purpose in doctrine(please correct me if I am wrong 🙂 ), and thus we have to create a query for this purpose, which can be as follows(You can use DQL as an alternative as well):


    /**
     * Return the number of records
     * @return integer
     */
    function get_count()
    {
        try
        {
            $query = $this->em->createQueryBuilder()
                            ->select("count(a)")
                            ->from("PdContact", "a")
                            ->getQuery();
            return $query->getSingleScalarResult();
        }
        catch(Exception $err)
        {
            return 0;
        }
    }
Code language: PHP (php)

Here, I will like to clarify for your better understanding that there is some similar functions named ‘getSingle’ and ‘getScalarResult’ also. As their name implies, ‘getSingleResult’ will retrieve a single record, which has a list of properties, and ‘getScalar’ will retrieve a list of records with a single property for each. So, for a single value(like count), we should use ‘getSingleScalerResult’ method.

Insert/Create operation:

I already shared a code snippet for this operation in my previous tutorial on using doctrine with codeigniter. However, that was in CodeIgniter format(taking the post input), so I am sharing it here again in regular format. Also, I will be writing the function in a little different way, and you will know the reason very soon. Here we go:


/**
     * Save contact message to database
     * @param array $contact_form
     * @return bool
     */
    function save_message($data,$id=NULL)
    {
        /**
         * @var PdContact $contact
         */
        if(empty($id)){
            $contact = new PdContact();
        }
        else{
            $contact = $this->get_single($id);
        }
        $contact->setName($data["name"]);
        $contact->setEmail($data["email"]);
        $contact->setSubject($data["subject"]);
        $contact->setMessage($data["message"]);

        try {
            //save to database
            $this->em->persist($contact);
            $this->em->flush();
            return TRUE;
        }
        catch(Exception $err){
            return FALSE;
        }
        return true;
    }
Code language: PHP (php)

Here I am assuming that you already have to validate the submitted data(in either post or get method) and passed them in a $data named associative array. For insert purpose, use this as follows:


$classname->save_message($data);
Code language: PHP (php)

the class name is where these codes are integrated. It needs to be remembered, and the second value is not supposed to pass in this case. Then, it will assume it as null and create a new entity, which will result in a new insertion in the database.

Update Operation:

here, actually, we won’t have to write anything new :D. The previous function will do our work by nature. to use that function for update purposes, follow this example:


$classname->save_message($data,$id);
Code language: PHP (php)

Also, for update purposes, the above-described function definition requires that the previous ‘get_single’ method is also in the same class. When the function is called with an id parameter, it will retrieve the corresponding record from the database, update the fields with new data and save it to the database.

Delete Operation:

Deleting an entity is somehow straight-cut way. Specify the entity and call ‘remove’ method on the entity manager. And flush the operation. Following is the code example for such a need, which I have generalized to accept either a single parameter or an array of parameters to ease deletion of single/multiple entities(s) in the same function:


     /**
     * Delete an Entity according to given (list of) id(s)
     * @param type $ids array/single
     */
    function delete_entities($ids){
        try
        {
            if(!is_array($ids))
            {
                $ids = array($ids);
            }
            foreach($ids as $id)
            {
                $entity = $this->em->getPartialReference("PdContact", $id);
                $this->em->remove($entity);
            }
            $this->em->flush();
            return TRUE;
        }
        catch(Exception $err)
        {
            return FALSE;
        }
    }
Code language: PHP (php)

Note the method call of “getPartialReference” . You could simply use “$this->get_single($id)” instead. However, in that case, it would retrieve the record from the database and then you would perform the delete operation. And now, with getting the partial reference, it won’t query the database at all. Thus, saving some query cost and optimizing the performance(it would be noticeably slow if you try to delete a lot of data at once).

I hope this doctrine crud tutorial will be helpful for you. Very soon, I am planning to write a few more tutorials on doctrine covering other features of it. So, be in touch. Ask me if you have any questions as well. Happy coding :).

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Database, Development Tagged With: doctrine, mysql, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. webof says

    August 9, 2013 at 4:03 am

    God bless you dude. You saved my life. I looked from videos to official docs of the Doctrine, they all suck. But this saved me. Really great tutorial. Hope you can do same for PHPUnit too 😉

    Reply
  2. warrioranish5 says

    December 5, 2016 at 5:43 am

    while performing select/read operation when i am trying to load retrieved data in view page following error occurs

    Fatal error: Cannot access private property PdContact::$name in C:\xampp\htdocs\doctrine\application\views\retrievedata.php on line 10

    how can i show them in view page.

    Reply

Trackbacks

  1. Custom Codeigniter Doctrine Model With Basic Functionality | codesamplez.com says:
    November 21, 2012 at 12:28 am

    […] On an earlier tutorial, I did showed how we can easily perform the CRUD operations using doctrine ORM. However, as a lot of developers use doctrine ORM as part of their favorite Codeigntier framework, […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023