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:
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
*/functionget_by_range($start=0,$length=10,$criteria = NULL,$orderby=NULL){
try
{
return$this->em->getRepository("PdContact")->findBy($criteria, $orderby, $length, $start);
}
catch(Exception $err)
{
returnNULL;
}
}
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
*/functionget_count(){
try
{
$query = $this->em->createQueryBuilder()
->select("count(a)")
->from("PdContact", "a")
->getQuery();
return $query->getSingleScalarResult();
}
catch(Exception $err)
{
return0;
}
}
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:
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:
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:
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
*/functiondelete_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();
returnTRUE;
}
catch(Exception $err)
{
returnFALSE;
}
}
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 :).
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 😉
[…] an earlier tutorial, I showed how we could easily perform the CRUD operations using Doctrine ORM. However, as a lot of developers use doctrine ORM as part of their favourite Codeigniter framework, […]
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
webof says
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 😉
warrioranish5 says
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.