Home Lists+

Scalable and Rapid Application Development Using Grails

Hi guys! Today we have a guest post from Boni Satani, you can find more about him at the end of this post, please read below!

Shorter time to market web application signifies being ahead of the competition. There are many factors that can contribute in shortening the lead time right from application conceptualization to implementation by increasing developer’s productivity which is the byproduct of the web application framework being used in the development.

There are many web frameworks that claims to develop web applications in weeks. However, the essence of choosing the development framework lies not only in developing quick but scalable applications.

Grails

In my opinion, Grails can fit the role of the right framework for developing quick and scalable applications. The following paragraphs will take you through the details of why Grails is the right choice for developing scalable and rapid applications.

Grails is an open source web development framework powered by Groovy programming language which is based on the Java Virtual Machine. Groovy gives benefits of being more productive through single lines of codes and shortens the learning curve. Moreover, Grails is built on software frameworks which includes Java Enterprise Edition (Java EE, JEE), Spring, Hibernate and Quartz allowing developers to easily integrate with other Java codes.

Grails is an MVC framework which is different from other development environments since it has a capability to hide the configuration details and has a ready to run template and custom tags and offers several other benefits to developers which results in reducing the overall time to market and building scalable applications. Let’s see how

Reduced Time to Market

Traditional Development vs. Rapid Application Development

When I say, reduced time to market, it means application development with Grails is quite fast. This happens due to several reasons such as:

  • Support from Other Java Frameworks: Groovy and Grails can be easily integrated with other Java platforms. This helps developers utilize the existing libraries with Groovy easily and quickly which help in processing the development speedily. 
  • Don’t Repeat Yourself: This principle is the base of Grails which means developers can make changes in the application without repeating or rewriting the codes and can concentrate on improving the quality of the application. Moreover, coding in Grails is lean and concise due to which there are fewer lines of codes adding to developer’s productivity. 
  • Convention Over Configuration: Grails works on Convention over Configuration principle which means it makes automatic assumptions as to what classes are needed, enabling developers to reduce the efforts in editing configuration files and managing databases. 
  • Tons of Plugins: Grails comes with tons of plugins which contribute in the core development. If you want to configure or integrate anything, you can do it right away with readily available plugins which reduces development time. 
  • Test Integration: Apart from these, you can easily integrate testing frameworks in your existing development cycle to test the applications simultaneously and reduce the overall development time.

Scalability

Applications developed in Grails are much more scalable and robust since Grails is based on Spring framework which is considered as a scalable framework in the enterprise world. Besides there are several other factors that contribute in making scalable applications with Grails.

  • Caching: Grail supports good caching solutions such as EhCache, MemCache and Guava library which provides an ability to cluster and make the applications available across multiple application services.
  • 'Enterprisey' & Cloud Tools: Using these tools, you can take your applications to the cloud very easily and make your applications accessible from any corner of the world.

All these features and benefits of Grails helps in making Grails the most preferable web framework for developing scalable applications in no time.

If you are a developer and looking for exploring a new technology for developing rapid applications, I would suggest you to try your hands at Grails. You can quickly learn its development architecture in a few hours by just referring a book and I promise you will be able to build fully functional web applications like never before using Grails.

You can also take a look at our whitepaper on Grails: Accelerating J2EE Application Development which gives in depth insight into how Grails helps in rapid J2EE Application development.

About Author:

Boni Satani is a Java Technology Consultant working with Cygnet Infotech. He has undertaken various Projects including Java Web Application Development and J2EE Application Development. You can connect with him over twitter at @bonirulzz

Home CakePHP

CakePHP 2.x Pagination Tutorial: Helper, Conditions, Limit, Sorting and More!

CakePHP Pagination is one of the fastest thing you can code with this amazing framework. In this post I’m gonna show you how you can create a pagination script in matter of few minutes, or even seconds! Cool? Let’s get started.

This post is part of my CakePHP tutorial series, before you proceed to this, make sure you already installed your CakePHP poperly, know the CakePHP classes and naming conventions, and much better if you can code the CakePHP CRUD operations.

Video Demo

Here’s a video demo of what will be our code ouput.

Controller Code

On our controller, we are going to have a query the cakePHP way, we are going to have the following conditions:

  • Won’t include the record with an ID of 6 (‘conditions’ => array(‘User.id !=’ => ’6′))
  • We will limit to 3 records per page (‘limit’ => 3)
  • Order the result by ID (‘order’ => array(‘id’ => ‘desc’)) in descending order

So here’s the code that will be added in our UsersController.php

public function view() {

    // we prepare our query, the cakephp way!
    $this->paginate = array(
        'conditions' => array('User.id !=' => '6'),
        'limit' => 3,
        'order' => array('id' => 'desc')
    );
    
    // we are using the 'User' model
    $users = $this->paginate('User');
    
    // pass the value to our view.ctp
    $this->set('users', $users);
    
}

The $users variable gives us an array that look like this:

cakephp-pagination

View Code

On our view.ctp, our data is presented with a table. The table header contains the paginator sort() method for sorting the data using any fields you want (and you won’t have to create another query!)

The $this->Paginator object (pagination helper) also has lots of methods for paging, please see the ‘pagination section’ on the code block below.

Also we used the <div class=’paging’> which uses the CakePHP generic CSS. You can change that if you want and be creative with your paging UI design.

<?php
// so we use the paginator object the shorter way.
// instead of using '$this->Paginator' everytime, we'll use '$paginator'
$paginator = $this->Paginator;

if($users){

    //creating our table
    echo "<table>";

        // our table header, we can sort the data user the paginator sort() method!
        echo "<tr>";
        
            // in the sort method, ther first parameter is the same as the column name in our table
            // the second parameter is the header label we want to display in the view
            echo "<th>" . $paginator->sort('id', 'ID') . "</th>";
            echo "<th>" . $paginator->sort('firstname', 'Firstname') . "</th>";
            echo "<th>" . $paginator->sort('lastname', 'Lastname') . "</th>";
            echo "<th>" . $paginator->sort('username', 'Username') . "</th>";
        echo "</tr>";
        
        // loop through the user's records
        foreach( $users as $user ){
            echo "<tr>";
                echo "<td>{$user['User']['id']}</td>";
                echo "<td>{$user['User']['firstname']}</td>";
                echo "<td>{$user['User']['lastname']}</td>";
                echo "<td>{$user['User']['username']}</td>";
            echo "</tr>";
        }
        
    echo "</table>";

    // pagination section
    echo "<div class='paging'>";

        // the 'first' page button
        echo $paginator->first("First");
        
        // 'prev' page button, 
        // we can check using the paginator hasPrev() method if there's a previous page
        // save with the 'next' page button
        if($paginator->hasPrev()){
            echo $paginator->prev("Prev");
        }
        
        // the 'number' page buttons
        echo $paginator->numbers(array('modulus' => 2));
        
        // for the 'next' button
        if($paginator->hasNext()){
            echo $paginator->next("Next");
        }
        
        // the 'last' page button
        echo $paginator->last("Last");
    
    echo "</div>";
    
}

// tell the user there's no records found
else{
    echo "No users found.";
}
?>

Thanks for reading this tutorial code for pagination in CakePHP!

Home CakePHP

CakePHP Classes and Naming Conventions

1.0 Introduction

After installing CakePHP on your server, we now have to learn how to create CakePHP classes and its naming conventions. CakePHP uses Model–view–controller (MVC) software architecture which is really great. If you have no idea what MVC is, I think Wikipedia can give you a great overview. Also, you’re going to get the hang of it in this post.

2.0 Creating CakePHP MVC Files

In this example, we are going to use a database with “users” table and create code for the model, view and controller files. Let’s have fun!

2.1 Preparing the user’s table

Our users table will have only 5 fields which include: id, firstname, lastname, username, password.

CakePHP Classes and Naming Conventions

CakePHP requires a naming convention for our tables. It must be in plural form always. Like right now, we are going to have a table that stores data of users, it means that the name of our table must be “users“, NOT the singular “user” or something.

2.2 Creating a Model

A CakePHP model class manages your application data, rules of validity (for example, a username is required, or a password must consist of letters and numbers) and interactions (queries, etc.).

To create our CakePHP model, go to your app/Model directory, I found mine in C:wampwwwCakePhpProjappModel

On that directory, we will create a model file named “User.php

cakephp-model-naming-convention

CakePHP requires us to create a model file with singular name and with a .php extention, that’s how we come up with the filename “User.php”

If your model has more than one word, for example you have a table “user_permissions”, our Model filename will be camel cased and will look like “UserPermission.php”

Inside that file, we are going to have the Model basic code:

<?php
class User extends AppModel {

    public $name = 'User';
    
}
?>

2.3 Creating a View

A view in CakePHP is the output representation of data retrieved from the model and manipulated by the controller. It can be in the form of HTML, XML, JSON or even PDF!

To create our CakePHP view, we have to go to the app/View/ directory and create a directory called “Users”.

cakephp-view-directory

And then after creating the directory, we will now create the actual “view”, as an example, we are going to have “hello_user.ctp” and leave it as an empty file for now.

cakephp-ctp-file

CakePHP requires us to name a view with a .ctp extension. A view’s name is the same as its function in the controller. We’re going to see it later.

2.4 Creating a Controller

A CakePHP controller class is like the middleman between the Model and View. Controllers are used to manage the logic around a model, and it uses the View for that logic’s output.

To create a model, we are going to create a file named “UsersController.php”

cakephp-controller-file

We are going to have the controller’s basic code:

<?php
class UsersController extends Controller {
    

    
}
?>

3.0 Making MVC Work

Now that we have the required directory, files and basic code inside them, we are going to make this MVC thing work.

3.1 Playing with the controller

First, open your controller, add the following code:

   public function hello_user(){
    
        $user = $this->User->findById(1);
        $this->set('user', $user);

    }

What just happened? As I said earlier, the view name (hello_user.ctp) will be the function name in the controller.

In this function, we tried to retrieve the record details of a user with an ID of 1.

$user = $this->User->findById(1);

To use the $user in the View, we have to use the $this->set() method. Yes, in CakePHP, passing variable values to view requires a $this->set() method.

3.2 Using the Model

For our model, we’ll leave it as is for now. It is used implicitly here in our example. How? Did you see the code $this->User in the controller? Yes, the “User” part of that code is the Model.

3.3 Viewing the View

Lastly, our view “hello_user.ctp” will present the data retrieved, we are going to have this code inside:

<?php
echo "Hello, " . $user['User']['firstname'] . "!";
?>

We retrieved the firstname like that. The $user variable gave us an array value, findById() method gave us this:

array(
    'User' => array(
        'password' => '*****',
        'id' => '1',
        'firstname' => 'Mike',
        'lastname' => 'Dalisay',
        'username' => 'ninjazhai'
    )
)

4.0 Run Code

Now here’s the exciting part, running our code. Go to your browser and type localhost/CakePhpProj/users/hello_user/

You should see something like.

cakephp-classes-name-convention-output

You might want to check out how to perform CRUD in CakePHP.

If you have any comment, suggestion or issues, just drop a comment below. :)

Home jQuery

jQuery: Sum TextBox Values As You Type

A friend asked me how to sum all TextBox value as he type the numbers?

Here’s a quick answer to that:

Give all your TextBoxes a class name and use the jQuery ‘keyup()’ and ‘each()’ methods to compute the sum.

HTML - a table where the product name and price TextBox is found.

<table>
    <tr>
        <td>Product Name</td>
        <td>Price</td>
    </tr>
    
    <tr>
        <td>MOBILE POWER BANK (2800MAH)</td>
        <td><input type='text' class='price' /></td>
    </tr>
    
    <tr>
        <td>DISNEY NECK REST PILLOW (CHIP)</td>
        <td><input type='text' class='price' /></td>
    </tr>
    
    <tr>
        <td></td>
        <td><input type='text' id='totalPrice' disabled /></td>
    </tr>
</table>

jQuery - methods we used include keyup, each and val. Read comments on code.

<script>
// we used jQuery 'keyup' to trigger the computation as the user type
$('.price').keyup(function () {

    // initialize the sum (total price) to zero
    var sum = 0;
    
    // we use jQuery each() to loop through all the textbox with 'price' class
    // and compute the sum for each loop
    $('.price').each(function() {
        sum += Number($(this).val());
    });
    
    // set the computed value to 'totalPrice' textbox
    $('#totalPrice').val(sum);
    
});
</script>

Complete Code:

<html>
    <head>
        <title>jQuery Sum Demo</title>
    </head>
<body>

<table>
    <tr>
        <td>Product Name</td>
        <td>Price</td>
    </tr>
    
    <tr>
        <td>MOBILE POWER BANK (2800MAH)</td>
        <td><input type='text' class='price' /></td>
    </tr>
    
    <tr>
        <td>DISNEY NECK REST PILLOW (CHIP)</td>
        <td><input type='text' class='price' /></td>
    </tr>
    
    <tr>
        <td></td>
        <td><input type='text' id='totalPrice' disabled /></td>
    </tr>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>

<script>
// we used jQuery 'keyup' to trigger the computation as the user type
$('.price').keyup(function () {

    // initialize the sum (total price) to zero
    var sum = 0;
    
    // we use jQuery each() to loop through all the textbox with 'price' class
    // and compute the sum for each loop
    $('.price').each(function() {
        sum += Number($(this).val());
    });
    
    // set the computed value to 'totalPrice' textbox
    $('#totalPrice').val(sum);
    
});
</script>

</body>
</html>

This post will be updated if any variation occurs. :)

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

Related Tutorials

Thank you for learning from our post about Sum TextBox Values As You Type in jQuery.

Home Lists+

Creating Social Media Icons for Your Website using CSS

In almost every website we see today, there are links to their social media accounts. I think it is a standard now. It’s like, you’re not cool if you don’t have a Facebook and Twitter account!

Recently, I was using Google drive to host my CSS and image files. Now, I removed it. Why?

Because Google drive slows down my website! During the use of Google drive hosted CSS and images, the average load time of this wesbite is around 10-20 seconds for new visitors.

After I removed it, it is now around less than 5 seconds!

Creating Social Media Icons for Your Website using CSS

My new social media icons. :)

I decided not to use any third party CSS code. I wanted to create my own social media icons, and I did! (see the screenshot above or the lower right corner of this page for live demo)

I think the icons I made are so cute that I thought of sharing it to you guys (I appreciate a tweet, like or +1 before you use it!). It loads fast, contains few lines of CSS and HTML code, and it doesn’t use any images! Here’s how I did it, below are the CSS and HTML code I used.

HTML code:

<div id="socialMediaIcons">

    <a class="facebook" href="https://www.facebook.com/CodeOfANinja" title="Facebook" target="_blank">f</a>
    
    <a class="twitter" href="http://twitter.com/ninjazhai" title="Twitter" target="_blank">t</a>
    
    <a class="googleplus" href="https://plus.google.com/b/101266899643014043497/101266899643014043497/posts" title="Google+" target="_blank">g+</a>
    
    <a class="rss" href="https://www.codeofaninja.com/feeds/posts/default?alt=rss" title="RSS" target="_blank">r</a>
    
    <a class="email" href="http://feedburner.google.com/fb/a/mailverify?uri=TheCodeOfANinja" title="Email" target="_blank">@</a>
    
</div>

CSS code:

#socialMediaIcons{
    margin: 0 auto;
    text-align:center;
}

#socialMediaIcons a{
    border-radius: 3px;
    color:#fff;
    font-family: arial;
    font-size:1em;
    height:2.5em;
    padding:1em;
    text-align:center;
    width:2.5em;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
}

#socialMediaIcons a:hover{
    color:#fff;
    text-decoration:none;
}

.facebook { background:#4c66a4; padding:2px 10px; }
.twitter { background:#33bcef; padding:2px 10px; }
.googleplus { background:#D2412E; padding:2px 3px; }
.rss { background:#fa9b39; padding: 2px 6px; }
.email { background:#00D8CC; padidng: 2px 6px; }

And… that’s how I created my new social media icons using CSS!

Home CakePHP

How To Use CakePHP Framework, A Getting Started Guide!

1.0 Introduction

Using CakePHP Framework is one of my most favorite things to do. This is the first PHP framework I worked with, and until now, I’m still delighted by it. Now it is time for me to share my knowledge in CakePHP web development.

I think you are here because you already know what CakePHP is, but for those who has no idea yet, and don’t want to read more on CakePHP.org, here’s a brief description: CakePHP makes building web applications simpler, faster and require less code.

I think there are really few blog posts out there with regards to beginner CakePHP tutorials. Most of them are also outdated. We will keep this CakePHP posts as updated as possible. So to the future reader of these posts, please drop something in the comment section below if you think there is something outdated!

We will start with the most basic thing to advanced. Hopefully I can finish this tutorial series in the shortest time possible.

2.0 Install CakePHP on Your Server

Below are few steps to make CakePHP alive in your hosting server, see sections 2.1 to 2.4 below.

By the way, if you’re a super beginner and using a windows PC (localhost), you can follow this tutorial first to set up your localhost: 3 Steps to Install WAMP on Windows

2.1 Download CakePHP (Step 1)

So… what do you expect the first step will be? Of course, we will download the framework. Download the latest CakePHP version here: http://cakephp.org/

As of this writing, the version is CakePHP 2.3.6 stable.

Extract the ZIP file.

2.2 Put CakePHP on Your Hosting (Step 2)

I don’t know, but I think most of you guys are using a localhost (your PC or something). Okay, so I’ll assume you are all using your localhost. If you’re not, just give a comment so we can try help you with your issue.

After you download and extract the Framework files, you have to put it in your root directory. I’m using windows 8 and running with WAMP server, so in my case, my root directory is in:

C:\wamp\www\

Now after putting the extracted folder, my CakePHP directory is in:

C:\wamp\www\cakephp-cakephp-b81c198\

Of course, we want to change the dirty name “cakephp-cakephp-b81c198″ to our “project name”.

So we have to rename it and for this tutorial, we will name it “CakePhpProj”, awesome name right? If you don’t think so, you can choose the project name of your choice. Now we should have:

C:\wamp\www\CakePhpProj

2.3 Run CakePHP

Too early to run? You’re correct. This is just a test run. We just want to confirm if CakePHP can respond at this stage.

So to run CakePHP: Go to your browser > type “localhost/CakePhpProj“

You might see something beautiful like this:

using-cakephp-first-run

You might be disappointed or intimidated by now, but don’t worry, I’m at your side! Proceed to the next step below.

2.4 Configure CakePHP

Alright, so we’re going to address the issues on the previous screenshot, one at a time!

2.4.1 URL rewriting is not properly configured on your server.- Let’s start with this problem, this error is rare if you’re using a real hosting. But if you’re using localhost, here’s the fix:

1. On you notification area (lower right corner), click the WAMP icon.
2. Hover your mouse to the “Apache” folder
3. Hover your mouse to the “Apache modules” folder
4. Find and click “rewrite_module”, WAMP will automatically restart and check that apache module.

mod-rewrite-cakephp

After the fix, re-run our project on the browser, it should look like this now:

cakephp-fix-rewrite-mod

2.4.2 Please change the value of ‘Security.salt’ - To solve this, you have to to got the core.php file and just change the security salt string!

In my case, I have to open it in C:\wamp\www\CakePhpProj\app\Configcore.php

Find the word “salt” (Ctrl+F on your editor, I’m using notepad++)

You should see the line of code that looks like:

Configure::write(‘Security.salt’, ‘DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi’);

Change the value to something like:

Configure::write(‘Security.salt’, ‘nowthisismyawesomesaltthatnoonecaneverknowxfs2gu’);

Then re-run the browser:

cakephp-fixed-security-salt

2.4.3 Please change the value of ‘Security.cipherSeed’ - The solution is the same with 2.4.2, just change the value and re-run!

cakephp-fixed-security-cypherseed

2.4.4 Your database configuration file is NOT present. – Now we have to make a database for our CakePHP application. If you need help doing that, here’s a guide: How To Create MySQL Database With PhpMyAdmin

After creating a database, we have to go again to the Config directory, in my case:

C:\wamp\www\CakePhpProj\app\Config

Now you should see a file named “database.php.default” and rename it to just “database.php“

After renaming it, we have to open it with our editor and supply the database details! In the $default array, what usually we have to change are the: database host, login (username), password and database

You would see something like this in default:

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'user',
    'password' => 'password',
    'database' => 'database_name',
    'prefix' => '',
    //'encoding' => 'utf8',
);

So we’re going to change it to:

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'root',
    'password' => '',
    'database' => 'my_project_database',
    'prefix' => '',
    //'encoding' => 'utf8',
);

Now, re-run our project page in the browser, it should look like this:

cakephp-installation-fix

3.0 Services

Still having hard time? I can personally help you do this for only $5!

That’s it for this post, enjoy and continue your CakePHP web development! Here is a continuation of this post: CakePHP Classes and Naming Conventions

Thanks for reading this How To Use CakePHP Framework, A Getting Started Guide!

Home Lists+

CSS3 Rotate Image On Hover

Have you seen our logo on the upper left corner? Try to hover on it, it will rotate 360 degrees. Looks cool? In this quick post, I’m going to show you how I did that using CSS3.

CSS:

#linkWrapRotator img {
     -webkit-transition: all 1s ease-in-out;
     -moz-transition: all 1s ease-in-out; 
     -o-transition: all 1s ease-in-out; 
     -ms-transition: all 1s ease-in-out; 
}

#linkWrapRotator img:hover { 
     -webkit-transform: rotate(360deg); 
     -moz-transform: rotate(360deg); 
     -o-transform: rotate(360deg);
     -ms-transform: rotate(360deg); 
}

HTML used:

<a href='https://www.codeofaninja.com/' id='linkWrapRotator'>
     <img src='https://lh6.googleusercontent.com/-Q0p2PeGBLLg/UTr5zOvggSI/AAAAAAAAEeM/SrYuO-cYWQU/s205/ninja-icon200x200.png' />
</a>

You can also do the rotation in other degrees, not on 360, just change the value of “rotate” in our code. For example, you can do rotate(180deg);

Just play with it!

Now that was fast and easy, I know there are other ways to do it, like using jQuery. There would also be some variations in doing this, such as not having a "a" tag.

Please share your own beautiful work, experience and cases on the comment section below!