How To Use Transaction In Database Operation In CakePHP 2.X

Sometimes we need to use the database transaction for saving the data in the tables for a complex application. Like booking online tickets for any show, movies, bus and planes.

In this case there will be some probability that the data will not be saved in the database due to a reason, like network failure, database inconsistency or table integrity etc.

There might be a case where data is saved partially in some tables and will create data inconsistency. The best example we can take here is ATM. i.e. you got a message that the amount has deducted from your account but you did not receive the money from the ATM.

To handle situations like this the CakePHP 2.x provides a feature transaction. Using transactions we cannot avoid the situation but can protect the harm it causes.

To perform a transaction, a model’s table must be of a data source and type which supports transactions.

All transaction methods must be performed on a model’s Data Source object. To get a model’s Data Source from within the model use:

[code language=”css”]
$dataSource = $this->getDataSource();
[/code]

You can then use the data source to start, commit, or roll back transactions.

[code language=”css”]</pre>
//Below code is responsible for begin the transaction
$dataSource->begin();

// Perform some tasks
if (/*all’s well*/) {
//This will commit the transaction on successful operation
$dataSource->commit();
} else {
//This will rollback the above operation in failure
$dataSource->rollback();
}
[/code]

Ex.

Let’s say we have a situation where we want to create a lead from the contact and send email to a customer after the contact gets saved in the database successfully.

Look at the below code to handle this situation.

So in CakePHP we have a model for tables. So for the contacts table we have “Contact.php” inside the model folder. Inside the “Contact.php” model, write the below code to handle transactions.

[code language=”css”]
//Transaction example
public function saveContactAndSendEmail()
{
$dataSource = $this->getDataSource();
try{
$dataSource->begin();
$aar[‘first_name’] = ‘John’;
$aar[‘last_name’] = ‘Doe’;
$aar[’email’] = ‘john.doe@gmail.com’;
if(!$this->save($aar)){
throw new Exception(__(‘Failed to save contacts data.’));
}else{
//Write the code to create a lead
$leadArr[‘lead_first_name’] = ‘John’;
$leadArr[‘lead_last_name’] = ‘Doe’;
$leadArr[‘lead_email’] = ‘john.doe@gmail.com’;
$Lead = ClassRegistry::init(‘Lead’);
if(!$Lead->save($leadArr)){
throw new Exception(__(‘Failed to save lead detail.’));
}else{
//send email that lead is created
}
}
$dataSource->commit();
}catch(Exception $e) {
//echo $e->getMessage();
$dataSource->rollback();
}
}
[/code]

Conclusion:

To perform a transaction, a model’s table must be of a data source and type which supports transactions. All transaction methods must be performed on a model’s data source object.

At Andolasoft we are very much experienced in handling the transmission issues in database. Consult now to solve your issues relating to same and other challenges in CakePHP. We have a team of experienced and dedicated CakePHP developers to help you. Hire us now!

Beginner’s Guide to Cropping Images in PHP Using ImageMagick

While using images in a web application, developers can’t always include images of a particular measurement. In such cases, resizing the images for the application would be a good option but, not efficient either. For example, resizing a long vertical image into a horizontal dimension would just squeeze the image; thereby, affecting the aesthetics of the website and also reducing the purpose of it. Hence it would be smart to implement a cropping tool like ‘ImageMagick’ in order to fit images of various dimensions into a specified size.

ImageMagick is a collection of robust and convenient tools for manipulating images. It can be used to crop images of numerous formats such as JPEG, PNG, GIF, TIFF, PhotoCD and many more. ImageMagick facilitates creation of dynamic images that are fitting to the specific requirements of web applications.

Difference Between Cropping in GD Library and ImageMagic:

GD is the most commonly used extension for PHP. It is popular because it is easier to install and configure (`yum install php-gd` on Fedora, CentOS etc or `sudo apt-get php5-gd` on ubuntu). However, it has some limitations such as:

  • It is comparatively slower
  • It is more memory intensive
  • For certain aspects it can be more complex to use.

Below I have mentioned a sample code for image cropping using GD:

[sourcecode]&amp;amp;amp;lt;?php
function resize_my_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width &amp;amp;amp;gt; $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newGDwidth = $w;
$newGDheight = $h;
} else {
if ($w/$h &amp;amp;amp;gt; $r) {
$newGDwidth = $h*$r;
$newGDheight = $h;
} else {
$newGDheight = $w/$r;
$newGDwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newGDwidth, $newGDheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newGDwidth, $newGDheight, $width, $height);

return $dst;
}

$img = resize_my_image(‘/path/to/some/image.jpg’, 150, 150);
?&amp;amp;amp;gt;[/sourcecode]

You can either output it to the browser or save it to a file using the ‘imagejpeg’ function.

Imagick:

Imagick is a less frequently used PECL extension. ImageMagick is a free tool that is used for creating and manipulating images that supports over 100 different image formats. This can be used on a command line tool for any programming language. The Imagick extension essentially provides an API for all of the functionalities available in the `convert` command line tool.

Some of its advantages are:

  • It is faster
  • It uses less memory
  • Offers more powerful functionality
  • Imagick’ is lot easier to use (once you figure out how), your code may end up smaller and cleaner.

The down side of using this extension is that the documentation is extremely limited and there are almost no examples available on the web. Installation on the other hand can be a painful task as well.

Although it should just be a matter of running the command `pecl install imagick`.

Sample code:

Cropping larger images:

Put a big picture named andolasoft_logo.jpg along side with your php page, run the test and check the directory to see andolasoft_logo_thumb.jpg.

Requirement:

imagemagick with imagick extension

[sourcecode]&amp;amp;amp;lt;?php
$obj = new imagick(‘andolasoft_logo.jpg’);
//resize the above image
$obj-&amp;amp;amp;gt;thumbnailImage(160, 0);
//write the thumb
$obj-&amp;amp;amp;gt;writeImage(‘andolasoft_logo_thumb.jpg’);
?&amp;amp;amp;gt;[/sourcecode]

To Crop Animated Image:

[sourcecode]&amp;amp;amp;lt;?php
$image = new imagick(“andolasoft_animated_logo.gif”);
$image = $image-&amp;amp;amp;gt;coalesceImages(); // the trick! To crop animated image
foreach ($image as $frame) {
$frame-&amp;amp;amp;gt;cropImage($width, $height, $x, $y);
$frame-&amp;amp;amp;gt;setImagePage(0, 0, 0, 0); // Remove gif canvas
}
?&amp;amp;amp;gt;[/sourcecode]

$x → The X coordinate of the cropped region’s top left corner
$y → The Y coordinate of the cropped region’s top left corner

Implementing ‘ImageMagick’ would make the website look clean and flawless. Images on the other hand retain its look and feel, thereby making the application look professional and optimized.

Find anything amiss here, then share it with us.