How to install Magento Step by Step in WAMP server?


Introduction:

My last article was “Google No Captcha reCAPTCHA”. . Magento is another most advance open source ecommerce platform. Its modular structure, flexibility and robustness made it very well known in PHP world. If you are beginner and wondering “How to install and configure Magento” then this article I will show you simple steps how to install Magento v1.9 into WAMP server.

Magento Installation & Configuration - Step by Step guide

Step 1:
Go to Magento website (http://www.magentocommerce.com/download) and download the magento community edition as your choiceble format. I have downloaded zip format.

Step 2:
Extract the zip file and paste it inside your www root directory. We will rename folder to magento as below screenshot.

Step 3:
Go to phpmyadmin and create a database called “magento”. This is where all magento tables will generate.

Step 4:
Before next step make sure curl extension enabled and max_execution_time increased in your php.ini file.

Step 5:
Open your browser and enter http://localhost/magento/ will display below page, agree terms and condition and click continue.

Step 6:
Next screen you will find Localization, you can keep as it is or change it later on from the admin panel. Click continue and you will be landed on configuration screen where you are required to give your database connection details as screen below. In my case I have configured database name as magento, username root and no password. Once you filled click continue to proceed next.

Step 7:
Next screen you may create admin account. That’s it. We are done with the configuration. You will find two button end of the page called “frontend” and “backend” as screen below. Save the encryption key in safe place.

You have successfully installed magento in WAMP server. You can click visit frontend by clicking frontend button and admin panel to manage store.

Conclusion:

Hope you found this article helpful. I will continue the magento series in my next posts. Upcoming tutorial you will find “How to do magento theme customization?”, “How to create custom module in Magento?” etc. Don't forget to like, share, or leave your comments below.

Stay tuned! Keep visiting for upcoming posts. Have a nice day.

Google introduced reCaptcha-“Are you a Robot ?” app using PHP


Introduction:

My last article was “Facebook style profile photo upload + Thumbnail Image + Saving into database”.

Bored looking at old Captcha test?

Google introduced latest security update “No CAPTCHA reCAPTCHA API” to protect your website from spam, robots and abuse. It is a complete redesign of Captcha system by Google. They made Captcha system very clear, easy to use. Simple checkbox to confirm they are human or not. Its sound very simple, but it is not, Google does all the magic behind the hood that makes this system more secure and reliable.

Impressive! I have implemented new API class with simple registration form using PHP and HTML. I would like to share with you all step by step.

You can have a look at the demo page, also can download the API class from below.

  Live Demo   Download

Step 1: To get reCAPTCHA Click Here

Step 2: Register your website domain to generate reCAPTCHA secret key as below.

Step 3: Click register to get reCAPTCHA secret key and site key. Store and keep it safe.


i. Use Site key in html code where you want reCAPTCHA should appear.
ii. Google Secret key to communicate with Google API service. Keep it safe place.


Step 4: Create a new page called index.php copy and paste below html code into it.



<!doctype html>
<html lang="en">
  <head>
  <meta charset="UTF-8" />
    <title>Google reCAPTCHA Demo</title>	
	<script src='https://www.google.com/recaptcha/api.js'></script>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
	<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,600,300,700" rel="stylesheet" type="text/css">
	<style type="text/css">
		.formbox { width:400px; height:auto;margin: 0px auto;padding: 20px;border: 1px solid #e5e5e5;box-shadow: rgba(200,200,200,0.7) 0 4px 10px -1px;margin-top:140px;}
	</style>	
  </head>  
  <body>
<?php
include 'lib/ReCaptcha.php';
include 'ActionController.php';
include 'database.php';

$dns = "mysql:host=localhost;dbname=google";
$username = 'root';
$password = '';
$secretKey = '6Lddzf4SAAAAALZFILTYX36qnXvKI3EQk3qDEIia';

$app = new ActionController(new ReCaptcha, new Database($dns,  $username, $password));

$error = "";

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    if (isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response'] !="") {
        $reCaptcha = $_POST['g-recaptcha-response'];

        $app->setGoogleSecretKey($secretKey);
    
        if (!$app->verify($reCaptcha)) {
            $error =  "Please enter your reCAPTCHA again!";
        }  else {
            $app->saveRegistrationInfo($_POST);
        }

    } else {
        $error = "Please check recaptcha before submiting form.";
    }
}
?>

  
  <div class="container" id="content">
  <div class="row formbox">
			<form action="" method="POST" role="form">
			
					<div class="form-group">
						<label class="col-sm-2 control-label">Username </label> 
									<input type="text" name="username" class="form-control" placeholder="Username"/>
					</div>
					
					<div class="form-group">
						<label class="col-sm-2 control-label">Password </label>
									<input type="password" name="password" class="form-control"  placeholder="Password"/>
					</div>
					
					<div class="form-group">
						<label class="col-sm-2 control-label">Phone</label> 
									<input type="text" name="phone" class="form-control" placeholder="Phone"/>
					</div>				
				  <!-- Your reCAPTCHA will appear here-->
				  <div class="g-recaptcha" data-sitekey="6Lddzf4SAAAAAHDKXw0TOcJoG_h-0APraljsIh8W"></div>
				  
				  <span class='msg'><?php echo $error; ?></span>
				  <br>
				  <input type="submit" name="btnSubmit" value="Submit" class="btn btn-sm btn-success">
				  
			</form>
	
	</div>
	
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</div>

  </body>
</html>


Step 5: Create a PHP file called /lib/ReCaptcha.php paste below code where we will validate reCAPTCHA via Google API and receive response.



class ReCaptcha
{
    public $captchaUrl = "https://www.google.com/recaptcha/api/siteverify";

    public $googleSecretKey;

    public $remoteIp;

    public function setReCaptchaSecretKey($key)
    {
        $this->googleSecretKey = $key;
    }

    public function getGoogleSecretKey()
    {
        return isset($this->googleSecretKey) ? $this->googleSecretKey : null;
    }

    public function validate($reCaptcha)
    {
        $url = null;
        $curlInfo = array();
        $url = $this->captchaUrl."?secret=".$this->getGoogleSecretKey()."&response=".$reCaptcha."&remoteip=".$_SERVER['REMOTE_ADDR'];

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);

        $curlInfo = curl_exec($curl);
        curl_close($curl);

        return $curlInfo;
    }

    public function process($reCaptcha)
    {
        $result =$this->validate($reCaptcha);
        return json_decode($result, true);
    }
}


Step 6: Create a file called ActionController.php via which we will interact with ReCaptcha API. Paste below code into it.



class ActionController
{
    private $connection;

    private $reCaptcha;

    final public function __construct(ReCaptcha $reCaptcha, Database $connection)
    {
        $this->reCaptcha = $reCaptcha;
        $this->connection = $connection;
    }

    public function setGoogleSecretKey($key)
    {
        $this->reCaptcha->setReCaptchaSecretKey($key);
        return true;
    }

    public function verify($reCaptcha)
    {
        $response= array();
        $response = $this->reCaptcha->process($reCaptcha);

        return $response['success'] ? true : false;
    }

    public function saveRegistrationInfo($data)
    {
        // Save information into database
    }
}


Step 7: Create a file database.php paste below code into it. This class act as wrapper class to manipulate database operation.



class Database extends \PDO
{
    public $db;
    
    public function __construct($dns,  $username, $password)
    {
        $this->db = parent::__construct($dns,  $username, $password);
    }
    
    public function getConnection ()
    {
        return isset($this->db) ? $this->db : null;
    }
}



[Note: Make sure curl extension enabled in your php.ini file.]

Using Javascript API for reCAPTCHA:

Another easiest way to integrate reCAPTCHA into your website is using javascript API. You can simply include api.js and div to render reCAPTCHA as below.



<div class="g-recaptcha" data-sitekey="your_site_key"></div>


Explicitly render using javascript onload



<html>
  <head>
    <title>reCAPTCHA demo: Explicit render after an onload callback</title>
    <script type="text/javascript">
      var onloadCallback = function() {
        grecaptcha.render('html_element', {
          'sitekey' : 'your_site_key'
        });
      };
    </script>
  </head>
  <body>
    <form action="" method="POST">
      <div id="html_element"></div>
      <br>
      <input type="submit" value="Submit">
    </form>
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
  </body>
</html>


Minimum Browser Requirement:

Chrome 3.0.195, Firefox 3.0, Internet Explorer 7.0, Opera 10.10, Safari 4.0

Conclusion:

Hope you found this article helpful. Don't forget to like, share with friends, or leave your comments below.

Keep visiting for latest posts. Have a nice day.

Facebook style profile photo upload + Resize Image + Saving into database


Introduction:

My last article was “How to build Facebook style profile photo upload using PHP + JQuery + Ajax Part1”. . This is continuation of my last article, last tutorial I show you how to upload profile picture using jquery, ajax, in this tutorial I will show you how to create thumbnail to fit the profile picture and saving into database.

Profile Picture Upload and Thumbnail Creation:

To achieve this I am using Cygnite PHP framework, if you had built application already, would like to use tiny component rather than using entire framework, you can use standalone Cygnite File component for image uploading and creating thumbnail image.



In previous tutorial we already created controller, view and js files. Open apps/controllers/ProfileController.php, import namespace to include thumbnail component, and add below code after uploading the file upload success to generate thumbnail image. I am adding piece of code to upload, creating thumbnail image and saving into database below, you can update below code into our ProfileController.php uploadAction() as discussed in the part1 tutorial.



use Apps\Models\Profile;
use Cygnite\Common\File\Thumbnail\Image; // available in dev-master 
use Apps\Components\Thumbnail\Image; //available in v1.2.4


$status = Upload::process(function($upload)
{
    $upload->file = 'document'; // Your file input element name
    $upload->ext = array("JPG", "PNG"); // Add validation for image upload
    //$upload->size = '6144';// limit the size

    if  (isset($_FILES['document']))  {

        $fileArray = array();
        $fileArray = pathinfo($_FILES['document']['name']);

        if ($upload->save(array("destination"=> "upload",  "fileName"=>$fileArray['filename'])) ) {

            // Create thumbnail object
            $thumb = new Image();
            $thumb->setRootDir(CYGNITE_BASE);
            $thumb->directory = 'upload/'.$_FILES['document']['name'];
            $thumb->fixedWidth = 100;
            $thumb->fixedHeight = 100;
            $thumb->thumbPath = 'upload/thumbnail/';
            $thumb->thumbName = $fileArray['filename'];

            if ( $thumb->resize() ) {

                // Save profile information into database
                 $profile = new Profile();
                 $profile->name = 'Sanjoy Dey';
                 $profile->original_image_path = CYGNITE_BASE.'upload/';
                 $profile->image = $_FILES['document']['name'];
                 $profile->thumbnail_image_path = CYGNITE_BASE.'upload/thumbnail/';
                 $profile->save();
            }

            $response= array('status' => true, 'msg' => 'Profile Picture Uploaded Successfully!' );
        } else {
            $response = array('status' => false, 'msg' => implode(', \n', $upload->getError()) );
        }
        header('Content-type: application/json');
        return  json_encode($response);
    }
});

echo $status ;



We are storing the thumbnail image into /cygnite/upload/thumbnail/ directory and saving into table 'profile'.

We will save the thumbnail image path and original image path into database as above. let me assume you have already set database connection into apps/configs/database.php

If you are building session based application. You can simply check user session id to identify user profile image and display it.

Using Standalone Cygnite File Thumbnail Component for creating thumbnail image:

If you are using standalone file thumbnail component to create thumbnail image (Discussed in previous post) than install file component from composer repository and below code to resize.


 require 'vendor/autoload.php';

 use Cygnite\Common\File\Thumbnail\Image;


 $thumb = new Image();
 $thumb->setRootDir(getcwd());
 $thumb->directory = getcwd().'/upload/profile-picture.jpg';// your dynamic image path
 $thumb->fixedWidth = 100;
 $thumb->fixedHeight = 100;
 $thumb->thumbPath = 'upload/thumbnail/';
 $thumb->thumbName = 'profile_thumbnail_image';
        
 if ( $thumb->resize() ) {
    // success
 }


Conclusion:

Hope you found this article helpful. If you are interested to write tutorial for us please post me. Please don’t forget to like, share with friends, or leave your comments below.

Keep visiting for upcoming article. Have a nice day.

Facebook style profile photo upload using PHP + JQuery +Ajax Part1


Introduction:

Hello guys, My last article was “How to build Facebook style Autocomplete using Angular JS, Cygnite PHP, Mysql and Bootstrap template” . Recently I received a request from one of my reader that “How to build Facebook style profile photo upload, creating thumbnail and save into server ?”. I will write the same here today. You might have notice in many social network site, in profile page when you mouseover in your photo "Update Picture" or "Upload Photo" displays. It's looks cool, as it is not displaying such old type of file upload html element. In this post I will not be able to cover whole tutorial. So I decided to divide the post into part. This tutorial will show you how to create "Facebook style profile photo upload using PHP, JQuery and Ajax."

To build this app, I am using Cygnite PHP Framework, JQuery, Ajax, Bootstrap template etc. Using framework make my job easier (Since bootstrap theme, inbuilt libraries, MVC, Widget etc), well structured, also gives flexibility to maintain code. If you don't wish use entire framework you can also use Cygnite File Component to do the same.

Installing Composer and Cygnite Framework:

So the first step is to install Cygnite framework to build our application, I will not write "How to install Cygnite into local machine", as it is covered in my previous article. Below links for Installation of Cygnite Framework but Cygnite v1.2.4 doesn't include File Upload feature, so please update composer.json to download latest framework code (dev-master) or manually update the framework core.

Cygnite Framework- Composer Installation

Manual Download from GITHUB

  Live Demo   Download

Step 1:
Let me consider you have already Cygnite installed into your machine. I have installed it into /www/cygnite/ directory. Now create a controller called ProfileController.php into your /cygnite/apps/controllers/ProfileController.php.

We will render the default view page using indexAction. We are not using layout here, but you can also use layout to make your view page much modular, flexible. Paste below code into your controller to call your view page.

 


namespace Apps\Controllers;

use Cygnite\Foundation\Application;
use Cygnite\Mvc\Controller\AbstractBaseController;
use Apps\Models\Country;
use Cygnite\Common\File\Upload\Upload;
use Cygnite\Common\UrlManager\Url;
use Cygnite\FormBuilder\Form;

class ProfileController extends AbstractBaseController
{
   protected $templateEngine = false;

   //Plain PHP layout
   //protected $layout = 'layout.base';
  /*
   * Your constructor.
   * @access public
   *
   */
   public function __construct()
   {
      parent::__construct();
   }

  /**
   * Default method for your controller. Render welcome page to user
   * @access public
   *
   */
  public function indexAction()
  { 
     $this->render('index');
  }


   // Upload profile picture
  public function uploadAction()
  {
    $status = Upload::process(function($upload)
    {
        $upload->file = 'document'; // Your file input element name
        $upload->ext = array("JPG", "PNG"); // Add validation for image upload
        //$upload->size = '6144';// limit the size

        if  (isset($_FILES['document'])) {

            if ($upload->save(array("destination"=> "upload",  "fileName"=>"user_profile_".time()))) {

                $response= array('status' => true, 'msg' => 'Uploaded Successfully!' );
            } else {
                $response = array('status' => false, 'msg' => implode(', \n', $upload->getError()) );
            }

            header('Content-type: application/json');
            return  json_encode($response);

        }
    });

    echo $status ;
  }
}


Step 2:
When you create a new controller you also need to create a folder into views/ as same name as controller but lowercase inside /cygnite/apps/views/ directory. I am creating my view page called index.view.php inside /apps/views/profile/index.view.php and paste below code to render our profile default image.



<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="col-sm-9">
    <form enctype="multipart/form-data">
        <div id="profile">
         <a href="javascript:void(0);">
             <img src="<?php echo Url::getBase(); ?>/assets/img/no_image.jpg" class="profile-image"  id="profileImg"/>
               <span id="uploadTrigger"><b>Update Picture</b></span>
               <input name="document"  type="file"  id="file-id" class="active"/>
             </a>
        </div>
        <div style="top:2px;"> </div>
        <div id="status_msg"> </div>
    </form>

</div>

Step 3:
Create a js file called profile.js into cygnite/assets/js/profile.js and paste below code. Cygnite is shipped with bootstrap so you can use it or use cdn link.



$(document).ready(function () {

    $("#uploadTrigger").on('click', function(event) {
        $("#file-id").trigger('click');
    });

//$('.hidden').removeClass('hidden').addClass( 'active');

$(":file").change(function() {

    var file = this.files[0],  name = file.name, size = file.size, type = file.type;
    //Your validation
    var imageType = new Array("image/png","image/jpeg", "image/gif", "image/bmp");

    if(jQuery.inArray(type, imageType )  == -1) {
        $("#status_msg").html("Valid file formats are: jpg, jpeg,png, gif").css('color', '#F00000');
        return false;
    }  else {

        $("#status_msg").html(" ");
        if ($("#file-id").val() !== '') {
            var formData = new FormData($('form')[0]);

            $.ajax({
                url: 'upload',  //Server script to process data
                type: 'POST',
                //Ajax events
                beforeSend: function () {
                    $('#profileImg').addClass( 'profile-image-loading')
                                    .removeClass('profile-image')
                                    .attr('src', '/assets/img/fb_loading.gif');
                },
                success: function (data) {

                    if (data.status) {
                        var reader = new FileReader();
                        reader.onload = function (e) {

                        $('.profile-image-loading')
                            .addClass('profile-image')
                            .removeClass('profile-image-loading')
                            .attr('src', e.target.result);
                           return false;
                        }
                        reader.readAsDataURL(file);

                        $("#status_msg").html(data['msg']).css('color', '#009900');
                    } else {
                        $("#status_msg").html(data['msg']).css('color', '#F00000');
                        return false;
                    }
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        } else {
        alert("Please select valid image.");
        return false;
        }
        }

});

});


Using Standalone Cygnie File Component for File Upload:

If you have already built an application and willing to use only standalone file component you can simply install Cygnite/File component using composer. I have installed composer globally in my system.

Create a composer.json file into your root directory where you want to install component, paste below code and save it.


{
  "require": {
    "php": ">=5.4.0",
    "cygnite/file" : "dev-master"  
  },
  "autoload": {
    "psr-0": {
        "Cygnite\\Common\\File": "cygnite/file/"
     }
   }
}


Now open terminal/command prompt, change to your project directory where composer.json exists and issue below command to install File Upload Component to do the same stuff.



composer install 


I am creating index.php file to access Cygnite File component, and below code to access File Upload feature.




require 'vendor/autoload.php';

use Cygnite\Common\File\Upload\Upload;

$upload = new Upload();

//$upload->setUploadSize(62092);
$upload->file = 'document';
$upload->ext = array("JPG");
$upload->size = '1024';

if(isset($_FILES['document'])) {

    if ( $upload->save(array("destination"=> "upload", /* "fileName"=>"demo_icon","multiUpload"=>true*/)) ) {
        $response = json_encode(array('status' => true, 'msg' => 'Uploaded Successfully!' ));
    }  else {
        $response = json_encode(array('status' => false, 'msg' => $upload->getError() ));
    }

    echo header('Content-type: application/json') .$response;exit;
}


Or you can also use Closure beautiful syntax as below.



require 'vendor/autoload.php';

use Cygnite\Common\File\Upload\Upload;

function fileUpload()
{
    $status = Upload::process( function($upload)   {
        $upload->file = 'document';
        $upload->ext = array("JPG");
        $upload->size = '5000000';

        if  (isset($_FILES['document'])) {

            if ( $upload->save(array("destination"=> "upload",  "fileName"=>"demo_".time(),/*"multiUpload"=>true*/)) ) {
                $response= array('status' => true, 'msg' => 'Uploaded Successfully!' );
            }  else {
                $response = array('status' => false, 'msg' => implode(', \n', $upload->getError()) );
            }

            header('Content-type: application/json');
            return  json_encode($response);
        }
    });

    echo $status ;
}


Now you can call the fileUpload function as usual in core php and calling this method in ajax url will process your ajax file upload. Don't forget to Include all above necessary css and jquery files in order to make the app work.

Finally go to browser and call the application by issuing below url.



http://localhost/cygnite/index.php/profile/


Conclusion:

We sincerely hope you found this article helpful. I will write “How to create thumbnail image / cropping to make image fit into profile area?” in my next post(part 2). If you would like to learn specific tutorial, you can also request tutorial or you are really interested to write tutorial for us please post me. Please don’t forget to like, share with friends, or leave your comments below.

Keep visiting for upcoming posts. Have a nice day.

Facebook Style Autocomplete Using Angular JS + PHP + MYSQL + Bootstrap


Introduction:

Hello guys, in my last article shown you "Generate CRUD application within 2 min" . Today I would like to share with you "How to build Facebook style Autocomplete using Angular JS, Cygnite PHP, Mysql and Bootstrap template”. Angular JS is awesome front end framework by Google used to build interactive web UI. Angular allow you to build clean structured, maintainable front end applications. This tutorial will help you to learn how to make autocomplete textbox using Angular JS, PHP, MySql, Bootstrap theme etc.

To achieve this we will also use Bootstrap UI with Angular JS. To save our time from writing queries and build clean MVC architecture we are also using Cygnite PHP Framework. You may use core php and mysql functions.

After downloading and installing composer we are ready to set-up Cygnite into our local machine and configure database etc. to get started with our next project.

Step 1:

First download the Cygnite either using composer or manually from GITHUB repository. You may also follow video tutorial to setup Cygnite into local system.

You may be interested to read Building A Simple Product Management App Using Angular JS + Cygnite PHP + Bootstrap

Step 2:

Download Angular JS, ui-bootstrap.js and paste into /assets/js/angular/ path. Create a view page called autocomplete.view.php into the apps/views/angular/ directory. Paste below code into your view page.



<!DOCTYPE html>
<?php
use Cygnite\AssetManager\Asset;
use Cygnite\Common\UrlManager\Url;
use Cygnite\AssetManager\AssetCollection;

$asset =  AssetCollection::make(function($asset)
{
  $asset->add('style', array('path' => 'assets/css/angular/bootstrap.min.css', 'media' => '', 'title' => ''))                
    /* ->add('script', array('path' => 'assets/js/cygnite/jquery.js'))
     ->add('script', array('path' => 'assets/js/angular/angular.min.js'))*/
     ->add('script', array('path' => 'assets/js/angular/ui-bootstrap.js'))
     ->add('script', array('path' => 'assets/js/angular/app.js'));
			
  return $asset;
});
?>
<html ng-app="MyTutorialApp">
<head>
<title>Facebook Style Autocomplete Using AngularJS + PHP + MySQL</title>
	
<?php $asset->dump('style');// Style block ?>
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,600,300,700" rel="stylesheet" type="text/css"> </link>
<link rel="shortcut icon" href="<?php echo Url::getBase(); ?>assets/img/cygnite/fevicon.png" > </link>

 </head>
 <body>
	
 <input type="hidden" id="baseUrl" value="<?php echo Url::getBase(); ?>"/>
    
 <div class="navbar navbar-default" id="navbar">
 <div class="container" id="navbar-container">
 <div class="navbar-header">
 <a href="#" class="navbar-brand">
 <small>
 <i class="glyphicon glyphicon glyphicon-log-out"></i>
   Angular JS Demo
 </small>
 </a><!-- Brand -->
		
</div><!-- /.navbar-header -->

	<div class="navbar-header pull-right" role="navigation">
        <a href="http://www.appsntech.com/2014/11/facebook-style-autocomplete-using-angular-js-php.html" class="btn btn-sm btn-default nav-button-margin"> <i class="glyphicon glyphicon-book"></i>&nbsp;Tutorial Link</a>
        <a href="https://app.box.com/s/yqyq0toxuo5n7ton0vol" class="btn btn-sm btn-success nav-button-margin"> <i class="glyphicon glyphicon-download"></i>&nbsp;Download Project</a>
	</div>
	</div>
	</div>
<div class="row">
	<div class="container">
	 <div class="col-sm-9"> 
	  <div>
	 <!-- Bind the country into the template -->
	<script type="text/ng-template" id="autocomplete-template">
        <a>
        <span bind-html-unsafe="match.label | typeaheadHighlight:query"></span>
	<i>({{match.model.country_name}})</i>
        </a>
	</script>

	<blockquote><h1><a href="http://www.appsntech.com/2014/11/facebook-style-autocomplete-using-angular-js-php.html">Facebook Style Autocomplete Using AngularJS + PHP + MySQL</a></h1></blockquote>

	<form class="form-search" ng-controller="angularAutocompleteController">
	Selected Country: {{selectedCountries.country_name}}
	<br>
	<!-- Typehead to input field-->
	<input type="text" ng-model="selectedCountries" auto-complete ui-items="countries"   
	placeholder="Search Countries" typeahead="c as c.country_name for c in countries | filter:$viewValue | limitTo:10" 
	typeahead-min-length='1' 
	typeahead-on-select='onSelectPart($item, $model, $label)' 
	typeahead-template-url="autocomplete-template" 
	class="form-control" style="width:350px;">
							
       <i class="icon-search nav-search-icon"></i>
      </form>
     </div>				
    </div>    	
   </div>
</div>
    
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>

 <?php
 //Script block. Scripts will render here
 $asset->dump('script');
 ?>
<style type="text/css">
.navbar{border-radius: 0;background: #438EB9;color: #fff;}
.navbar .navbar-brand {color: #FFF;font-size: 24px;text-shadow: none;}	
</style>	
    </body>
</html>


We are binding the typehead into the input field.

Step 3:

Create a model class called Country.php into apps/models/Country.php and paste below code.


namespace Apps\Models;

use Cygnite\Database\Schema;
use Cygnite\Foundation\Application;
use Cygnite\Common\UrlManager\Url;
use Cygnite\Database\ActiveRecord;

class Country extends ActiveRecord
{

    //your database connection name
    protected $database = 'tutorials';

    // your table name here (Optional)
    protected $tableName = 'countries';

    protected $primaryKey = 'id';

    public function __construct()
    {
        parent::__construct();
    }
}// End of the ShoppingProducts Model

Step 4:

Configure database connection into your apps/configs/database.php. Than Create a controller called AngularController.php inside your apps/controllers/ directory and paste below code.



namespace Apps\Controllers;

use Cygnite\Foundation\Application;
use Cygnite\Mvc\Controller\AbstractBaseController;
use Apps\Models\Country;

class AngularController extends AbstractBaseController
{
    protected $templateEngine = false;
     /*
     * Your constructor.
     * @access public
     *
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Default method for your controller. Render welcome page to user.
     * @access public
     *
     */
   public function indexAction()
   {    
        $this->render('autocomplete');//Render view page
   }
   
   public function countryListAction()
   {
      $countryList = array();
      $country = new Country();
      $countryList = $country->select("*")->findAll('ASSOC');
  
       if (count($countryList) > 0 ) {
    # JSON-encode the response
    echo  json_encode($countryList);
       }
   }

}//End of your controller



Step 5:

Create a table called “countries” and import countries.sql from here.

Step 6:

Now create a js inside your /assets/js/angular/app.js and paste below code. In this file we will inject bootstrap ui module and use ajax to fetch countries from the database and we will bind the countries into the input field.

 

var app = angular.module('MyTutorialApp',  ['ui.bootstrap']);

app.controller('angularAutocompleteController', function($scope, $http) {

var baseUrl = $("#baseUrl").val();
 
 getCountryList(); // Load all countries with capitals
  
  function getCountryList(){  
  
  $http.get(baseUrl+"angular/country-list").success(function(data){
      
        $scope.countries = data; // set the data into the countries
  
    });
    
  };
  
});


Step 7:

Go to browser and enter the url http://localhost/cygnite/angular/ type the country name and you will see countries are populating into the textbox.

Conclusion:

We sincerely hope you found this article helpful. I will write more about angular coming days. If you would like to see specific you can also request tutorial. Please don't forget to like, share with friends, or leave your comments below.

Keep visiting for upcoming articles. Have a nice day.

Generate CRUD application within 2 minute


Introduction:

Hello guys, my last article was about "How to install and configure Cygnite PHP Framework using Composer". Today I would like to share a tutorial which will help you day to day activity, also boost up your development. Generating CRUD application is day to day task for almost every developer. Why to spend numerous times on writing CRUD when it is just a 2 minute job to boost up your productivity. Generate you all necessary code for your project as like – INSERT, UPDATE, DELETE, Pagination, Sorting and Field Validation with bootstrap theme etc within just 2 minute.

Sound Interesting? Yes.

Cygnite PHP Framework makes your job easier with fun at working. Learning new framework is fun and gives you learning curve. So let me show you how you can generate all above functionalities with in just 2 minute.

Step 1:

Install Cygnite Framework into your local machine. Set up your database into apps/configs/database.php file

Step 2:

Cygnite CRUD is fully model based. So have your table ready against which you would like to generate CRUD. Or you can use Cygnite Migration to create table schema. Migration is the best practice to build schema but let me not go into Migration in this tutorial. I will explain Migration and seeding another post.

Step 3:

Open your command prompt or terminal. Change the directory to your project root. For example (I am using Windows) if we have installed cygnite into G:\\wamp\www\cygnite\ then you need to enter



 cd wamp/www/cygnite


We are going to use Cygnite CLI to generate CRUD application so now we need to change directory to



 cd console/bin


Okay cool! Now we are inside cygnite/console/bin then run below command to generate your CRUD application. Let us assume we are generating crud for table called “user_info”, database name "directory" and we want the controller name as “User”. So our command should be as follows.



 php cygnite generate:crud user user_info directory


The above command will generate you CRUD application as Controller, Model, Views, Form Component etc. You can find the files corresponding directories as below.

Controller:



     • cygnite/apps/controllers/UserController.php

Model:



     • cygnite/apps/models/UserInfo.php


Views:



     • cygnite/apps/views/user/index.view.php
     • cygnite/apps/views/user/create.view.php
     • cygnite/apps/views/user/update.view.php
     • cygnite/apps/views/user/view.view.php


Form Component:



     • cygnite/apps/components/form/UserForm.php


You can alter any code to make it fit for your project. That’s all! You are ready to see your application. Go to your browser and type http://localhost/cygnite/user/ you will find your application.

The complete code generation even takes less time if you have configured everything and simply to run crud command.

Conclusion:

Hope you found this article useful and make your life easier. Please post me if you have any queries. If you find above tutorial helpful, please don't forget to give a small like or share with friends, also leave your comments below. I really appreciate feedback regarding this CRUD generator from my readers.

Keep visiting for upcoming articles. Cheers! Have a nice day.

How to install and configure Cygnite PHP Framework using Composer


Introduction:

Hello guys, my last article was about "Facebook style wall posting using Cygnite PHP Framework, JQuery, Ajax" . Today I would like to share with you guys "How to install and Configure Cygnite PHP Framework using Composer". Composer is the awesome tool to manage your dependencies. Learning new framework is always adventurous and gives you a big learning curve.

Before going into the installation you should have composer installed in your local system. There is a beautiful documentation of Installation.

After downloading and installing composer we are ready to setup Cygnite into our local machine and configure database etc. to get started with our next project. You can watch the video embedded below.

Conclusion:

Hope you found this article useful. Please don’t forget to give a small like or share with friends, also leave your comments below.

Keep visiting for upcoming articles. Cheers! Have a nice day.

Facebook style wall posting using Cygnite PHP Framework, Jquery, Ajax


Introduction:

The last article was about “Reading and importing CSV file into database using PHP” . Today I have interesting thing for you guys. Are you looking for social script as facebook comment posting with MVC architecture? Which contains share thoughts on wall, comment posting, delete using jquery, load more, ajax, you want to share Facebook like video. You may get many script from different sites but mostly paid and not modular MVC architecture and you will end up restructuring into MVC. So I thought to share with you the application where you will find all these features and many more on coming days. Also you can find the script hosted on GITHUB.

Step 1:

Download and extract (wallscript-master.zip) the code from GITHUB. Rename wallscript-master to wallscript.

Step 2:

Configure your database name into /wallscript/apps/configs/database.php. I have configured database: “tutorials” localhost with empty password, you can change if you have different.

Step 3:

Find the demo sql script inside /wallscript/apps/database/wallscript.sql. Run the sql file into your database using phpmyadmin or Mysql Workbench.

Step 4:

That's all. You are done. Now go to your browser and type url : http://localhost/wallscript/ You can see the screen as below.


Extract video from url:



 

Conclusion:

Hope you will like the small app. Top of this script you can build implement much modular features as Facebook or any other social network has. Will add more features. Stay tuned!

If you find above tutorial helpful, please dont forget to give a small like or share with friends, also leave your comments below. Have a nice day. Keep visiting for interesting articles.

Reading and importing CSV file into database using PHP


Introduction:

Hi guys, my last article was about "Building RESTful Web Service using Cygnite PHP Framework, MySQL" . Today I would like to write about “Reading csv file using php”. This article may be useful for beginners or if you are willing to write flexible CSVReader library. Let me show you how you can read and return simple array as Column and value pair using simple line of code.

Step 1: Reading CSV file:

Create a file call CsvReader.php and paste below code.



 function readCsvToArray($path, $delimiter = ';')
    {
        $csvArray = $headerArray = $csvFilledArray = array();

        if (($handle = fopen($path, "r")) !== FALSE) {
            $i = 0;
            while (($dataArray = fgetcsv($handle, 4000, $delimiter)) !== FALSE) {

                $count = count($dataArray);

                for ($j=0; $j< $count; $j++) {

                    if ($i ==0) {
                        $headerArray[$i][$j] = str_replace(' ', '_', $dataArray[$j]);
                    } else {
                        $csvArray[$i][$j] = $dataArray[$j];
                    }
                }

                if ($i != 0) {
                    $csvFilledArray[$i] = array_combine($headerArray[0], $csvArray[$i]);
                }

                $i++;
            }
            fclose($handle);

            return $csvFilledArray;
        }
    }



Step 2 : Returning output as Array:

Now include the library file and call the function. Find the demo CSV file here.



require 'CsvReader.php';
$path = 'country_csv_reading_using_php.csv';

$csvArray = array(); 
$csvArray =  readCsvToArray($path, ‘;’);

echo "
";
print_r($csvArray);
echo "
";

Step3: Importing data into Mysql Database:

Let us consider our table is “CountryInfo” and table has columns as follows.



"Sort_Order", "Common_Name", "Formal_Name", "Type",
"Sub_Type", "Sovereignty", "Capital", "ISO_4217_Currency_Code",
 "ISO_4217_Currency_Name", "ITU-T_Telephone_Code", "ISO_3166-1_2_Letter_Code", 
"ISO_3166-1_3_Letter_Code", "ISO_3166-1_Number", "IANA_Country_Code_TLD"



Now we can loop throw the array and insert values into the database.

Paste below code to prepare all queries together and execute it.



$sql = '';

$sql = 'INSERT INTO `CountryInfo` (`Sort_Order, `Common_Name`, `Formal_Name`, `Type`,
      `Sub_Type`, `Sovereignty`, `Capital`, `ISO_4217_Currency_Code`,
      `ISO_4217_Currency_Name`, `ITU-T_Telephone_Code`, `ISO_3166-1_2_Letter_Code`, `ISO_3166-1_3_Letter_Code`,
      `ISO_3166-1_Number`, `IANA_Country_Code_TLD`) VALUES';

$data = array();

foreach ($csvFormatedArray as $key => $value) {

    $data[] = " VALUES ( '".$value['Sort_Order']."', '".
                  $value['Common_Name']."', '".
                  $value['Formal_Name']."', '".
                  $value['Type']."', '".
                  $value['Sub_Type']."', '".
                  $value['Sovereignty']."', '".
                  $value['Capital']."', '".
                  $value['ISO_4217_Currency_Code']."', '".
                  $value['ISO_4217_Currency_Name']."', '".
                  $value['ITU-T_Telephone_Code']."', '".
                  $value['ISO_3166-1_2_Letter_Code']."', '".
                  $value['ISO_3166-1_3_Letter_Code']."', '".
                  $value['ISO_3166-1_Number']."', '".
                  $value['IANA_Country_Code_TLD']."' )";
}

if (count($values)) {
    $sql = $sql.implode(',', $data);
    # build query
}



As the "Best Coding Practice" you can see we are not doing any database operation inside the loop, building the query and finally executing as single query. By doing this you are not running n number of queries instead single optimised query to save all.

Step 4: Inserting into database:

Let us now connect with the database and import csv content into database.



try {
    $conn = new PDO("mysql:host=localhost;dbname=tutorials", 'root', '');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
    $q = $conn->prepare($query);
    $q->execute();
} catch(PDOException $e) {
    echo $e->getMessage();
}


Conclusion:

Hope enjoyed the post and you can build modular library on the top of this small step by step article.

If you find above tutorial helpful, please don’t forget to give a small like or share with friends, also leave your comments below.

Have a nice day. Keep visiting for interesting articles.

Building RESTful Web Service using Cygnite PHP Framework, MySQL


Introduction:

Hi guys, my last article I wrote about “Getting started with MySql event scheduler” .Now days most of the applications building in mind that we can also access data using cross device like mobile, web application. Shortly Web services are talking over the application world. So far I have developed many web service api which is interacting with mobile, tablet device to access data from the server. Today let me explain how to build a better REST api using Cygnite PHP Framework.

REST - Representational State Transfer

Building REST web service is very easy and also you can use the power of mvc architecture of Cygnite Framework to build powerful RESTApi services.

Installing Cygnite PHP Framework:

Install Composer into your system. Composer installation is the recommended way to install Cygnite PHP Framework or you may manually download it from git hub repo . Cygnite has beautiful documentation will lead you to quick start.



composer create-project cygnite/cygnite-application cygnite --prefer-dist


Make sure you have composer install in your system.

Configuring Database:

Let us configure the database connections before stepping into web service.

 


/apps/configs/database.php

use Cygnite\Database;

Configurations::initialize(
    function ($config) {
        $config->setConfig(
            array(
             'db'  => 'mysql://root:webservice123@localhost/webservice_tutorial?charset=utf8'
            )
        );
    }
);


We are done with database settings; let us move to routing to response to web service request.

Routing- RESTful Service:

Cygnite has powerful routing to respond to your REST service calls. Even you can make use of full featured MVC to respond to your request. In this article I will show you how to respond to your HTTP get method calls and return users as json array.

Step1: Responding to post request and calling controller:

Open apps/routes.php and paste below code to get the list of users from the database.



$router->get(
    '/webservice/api/get-user',
    function () {
        $data = file_get_contents("php://input"); 
        echo Router::call('Webservice.index', array("request" => $data));// call Webservice controller index method
        Router::end();
    }
);

Step2: Controller and Getting User Details using Model:

Create a controller called WebserviceController.php into apps/controllers directory and paste below code into your index method. It should be look like below.



namespace Apps\Controllers;

use Cygnite\Foundation\Application;
use Cygnite\Mvc\Controller\AbstractBaseController;
use Apps\Models\User;

class WebserviceController extends AbstractBaseController
{

    public function __construct()
    {
        parent::__construct();
    }


    /**
    * Default method for your controller. We will return Users as json format
    * @access public
    *
    */
    public function indexAction($request = array())
    {
       $request  = json_decode($request);
  
       if (isset($request['request']->USER_STATUS)) {   

       $users = User::findByStatus($request['request']->USER_STATUS);  
       $users = (array) $users;

         if (!empty($users)) {

             foreach ($users as $key => $value) {
                $data[] = $value->user_name;
             }

            $response = array("data" => $data);

         } else {
            $response = array("error" => "There are no active users");
         }

       } else {
              $response = array("error" => "Invalid request format");
       } 
  
       return json_encode($response);
    }
}//End of the controller


Step3: Creating model to get Users:

I have a table called user into the webservice_tutorial database. So let us create the model called User and paste below code. Remember your table name model name should be same. For more info you may have a look at the documentation.



namespace Apps\Models;

use Cygnite\Database\ActiveRecord;

class User extends ActiveRecord
{
    //your database connection name
    protected $database = ‘webservice_tutorial’;
 
    protected $primaryKey = 'id';

    public function __construct()
    {
        parent::__construct();
    } 
}


Step4:

That’s all. We are done. Just go to your rest client in and type the post url to get the result. You can see screenshot below we got the list of users from the database.

Conclusion:

Similar way you can respond to POST, PUT, GET, DELETE, etc. Hope this article useful. If so please don’t forget to give a like or share with friends, also leave your comments below. Have a nice day. Keep visiting for upcoming posts.

Getting Started With Mysql Event Scheduler


Introduction

Hi guys, my last article I shown you “How to generate database oriented Form using Cygnite simple command”. Today I would like to write about MySql Event Scheduler. MySql Event Scheduler very useful concept if you are dealing with large scale application like email system, online shopping, or may be activity history management application. Where every day thousands of data getting stored into the database which create a heavy load into your database and slow down your application. You may no longer required existing activity history or want to archive data, this is where Mysql Event scheduler come to play. Event useful to create backup, delete unnecessary rows from database so on. Let me show you how to start with Mysql scheduler.

Creating a Table:

Let us create a sample table activity_history to store each and every activity of user in the application. You may compare with similar stuffs at facebook where each and every user activity displays at right top corner.


CREATE TABLE activity_history 
(
id INT(11) AUTO_INCREMENT,
user_id INT(11),,
description INT(11),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);


Enabling Event Scheduler:

Before creating or scheduling event you need enable event by executing below command.


SET GLOBAL event_scheduler = ON;
              or
SET GLOBAL event_scheduler = 1;


Similarly you can also turn off the event as below.



SET GLOBAL event_scheduler = OFF;


Confirming Event

After enabling you may confirm your event by



SHOW PROCESSLISTG


Creating Event:



CREATE EVENT delete_activity
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM activity_history WHERE created_at <= DATE_SUB(NOW(), INTERVAL 15 DAY) ;


Above event will run every day and delete 15 days old activity history from the table.

Altering Event:

Suppose you want to alter the old event you can do as below.



ALTER EVENT delete_activity
    ON SCHEDULE EVERY 1 MONTH
    STARTS '2014-07-01 01:00:00'


If you would like to rename Event



ALTER EVENT delete_activity RENAME TO delete_activity_event;


Displaying Mysql Events:

Below command will display all the events available into your database.



SHOW EVENTS;


Deleting Event:

You may delete unnecessary event by executing.



DROP EVENT delete_activity_event;


Conclusion:

Hope this article useful. If so please don’t forget to give a small like or share with friends, also leave your comments below.

Have a nice day. Keep visiting for latest posts.

Generate Form Class Using Cygnite Form Generator Comand


Introduction

Hi guys, my last article was about “Getting started with PHP dependency manager Composer”. Today I would like to introduce you with another best tool to generate forms, Cygnite Form generator. Writing html form is old fashion, now days most of the passionate developers does same thing object oriented way. Cygnite Framework CLI gives you breeze and make your development amusing. In some case you may don’t want to generate entire crud operation which Cygnite does cool way.

You are looking for Form generator?

Cygnite CLI is the great tool to cater your development time, generate you form based on your database table with single line of console command. Sounds interesting? Yes.

Let me show you how to get started with forms, before that you need to know folder structure, database configuration etc. with some simple steps.

Cygnite Framework: Folder Structure

Database Configuration

Open database.php file and provide your database configuration as below.

 


use Cygnite\Database;

Configurations::initialize(
    function ($config) {
        $config->setConfig(
            array(
             'db'  => 'mysql://username:password@hostname/database_name?charset=utf8'
            )
        );
    }
);

This is one time configuration. You are ready to generate your awesome forms. Remember all your forms will be generating based on your table exists into your database.

Cygnite CLI: Running Form Generator Command

We are ready. Open your console window, Command prompt if you are using Windows and terminal if you are using Ubuntu or linux.

Changing directory. Go to your Cygnite root directory as below. I have installed Cygnite into cygnite-app.



cd /var/www/cygnite-app/console/bin/


Now let us generate form against registration table.

Run below command and press enter.



 php cygnite generate:form table_name database

    or 

 php cygnite generate:form registration// Default database connection


Finding and Rendering Form

You can find your form class inside your form component directory. You can see /cygnite-app/apps/components/form/RegistrationForm.php generated. You can generate and access your form as below.



use Apps\Components\From\RegistrationForm;

$form = new RegisterForm(); // create a form object

echo $form->buildForm()->render(); // render your registration form.


Isn’t simple? You may alter the form based on your need. You may have a look at the documentation if you need further detail information about Cygnite Form Builder to alter form elements.

Conclusion:

Hope it is useful, once you are ready with database; you are ready to generate n number of forms. Cygnite Framework is under active development and your suggestions and feedback will help us to fulfill all your needs.

If you find above tutorial helpful, please don’t forget to give a small like or share with friends, also leave your comments below.

Have a nice day. Keep visiting for interesting articles.

Getting started with PHP dependency manager Composer


Introduction

Hi Guys, my last article was about “Creating custom Jquery Plugin”. Today I would like to introduce you with another best project in PHP world, Composer. Today’s PHP is not like grandfather PHP, it is completely different, much more matured, elegant and ready for enterprise development. So the question is why Composer? How to manage package with composer?

Yes, composer is the great tool to manage your project dependencies, keep you updated with the dependencies. It get you the package needed for your current version and also download, manage if that package use other packages. Most of the modern frameworks are Composer powered, few examples – Cygnite PHP Framework , Zend , Symfony etc. So you are having freedom to use any third party library into your framework.

The main feature is package can be written such a way that can be usable or pluggable into any other application supported by composer.

Step1: Installing Composer

Though there is a beautiful documentation in the composer website , if you are looking for short installation and usage tutorial you can start looking at steps below.

 

curl -s https://getcomposer.org/installer | php


Above command will download composer.phar into your current location.

To make composer globally accessible.



sudo mv composer.phar /usr/bin/composer


This command will help you to move composer.phar into bin directory and giving you access to all composer commands with much shorter syntax.

For example:



composer.phar --version


Can be run as


composer –version


If you are Windows user you may download and run composer.exe.

Step2: Using composer.json

If you aware about the ruby (gem) or node.js (package.json) then composer.json may be familiar to you. It mostly inspired by ruby bundler and package.json. Composer uses json file to provide settings and package information for your awesome application.

Create a file into your root directory called composer.json and paste the below lines.



{ 
    "require": { 
        "cygnite/framework": "1.*"
    }
}


Above example is for basic composer settings. The require keyword used for providing list of dependencies of your project. You can see in this example dependency is Cygnite Framework version 1. Cygnite Framework dependent on very few packages composer will install those automatically when you run below command into command line interface in the directory where your composer.json file exits.



 php composer.phar install
      or 
 composer install 


You can see composer is downloading Cygnite Framework and its dependencies one by one. Interesting right!

You can also see composer.lock file into your directory which is used to track all version of packages currently installed. If you change anything in composer.json file you may run below command to keep you up to date.

 
 
 composer update

 
 

Now go to the project directory and you can see vendor folder where composer installed packages. Composer also follows PSR-0 autoloader to autoload all your dependencies. You can see file called vendor/autoload.php

You can simply use autoload.php into your project and start using the package.

 

 require_once "vendor/autoload.php";
 
 
 

Step3: Sample Usage of Autoloader- Using Cygnite Asset Manager

Step2 we have installed all packages using composer, now let me show you how you can make use of those composer packages into your project.

Create a index.php file and paste below code and make sure assets exists into your application directory. Sample usage below.

  

require_once "vendor/autoload.php";

define('CF_SYSTEM', 'CYGNITE-ASSET');

use Cygnite\AssetManager\AssetCollection;
use Cygnite\AssetManager\Asset;

$asset =  AssetCollection::make(function($asset)
{
    $asset->add('style', array('path' => 'composer-tutorial/assets/twitter/bootstrap/css/bootstrap-theme.min.css'))
                ->add('style', array('path' => 'composer-tutorial/assets/twitter/bootstrap/css/bootstrap.min.css', 'media' => '', 'title' => ''))
                ->add('style', array('path' => 'composer-tutorial/assets/css/stylesheets/*'))
                ->add('script', array('path' => 'composer-tutorial/assets/js/cygnite/jquery.js'))
                ->add('script', array('path' => 'composer-tutorial/assets/js/custom.js'))
                ->add('script', array('path' => 'composer-tutorial/assets/twitter/bootstrap/js/bootstrap.js'));

    return $asset;
});

$asset->dump('style');
$asset->dump('script');


Conclusion:

You would have heard about the composer but haven’t had time to check. So I hope you have learned something today. Composer is very useful Dependency Management tool in PHP world. If I missed anything above you may also have a look at Composer official documentation.

If you find above tutorial helpful, don’t forget to give a small like or share with friends and also leave your comments below. Keep visiting.

How to create own custom JQuery Plugin?


Introduction:

My last article was about “How to auto reload page content using Jquery, Ajax and PHP”. Today I will show you how to create your own custom plugin using Jquery.

Many times we simply code according to current need on the project and may be same repetitive code in the next project. Why to code multiple times? If you feel some functionality can be used in future task as well then instead just fulfilling current project needs, you can create a plugin which can be used anywhere in any project.

What if we code once and use it all over where ever it is applicable? Sound interesting! yes. You are able to save your time by this way. If you are still wondering how to create Jquery plugin then here is the simple steps by which you can get some idea to create your own custom plugin and how to bind data into the div using Jquery.

Step1: Create a file called index.html and inside your html body paste the below code.



<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> 
<script src="js/custom-plugin.js" type="text/javascript"></script> 

<script type="text/javascript">
    $(function(){

        //data binding
        $("#search").on("keyup keypress blur change" , function(){
           // Custom Plugin
           $(this).helloWorld({
                id        :  'hello-text' ,
                text      :  $("#search").val(),
                color     :  '#005dff',
                fontStyle :  'italic'
           });
        });
        
    });
</script>   

<input type="text" id="search" />
<div id="hello-text"></div>


Step2: Create a file called custom-plugin.js and paste the below code.

 

/**
 * @Author Sanjoy Dey
 * @param {type} $
 * @returns {undefined}
 */

(function($) { 
    
    $.fn.helloWorld = function(options) {
        
         // establish our default settings
        var settings = $.extend({
            id           : 'search',
            text         : 'Hello World!',
            color        : null,
            fontStyle    : null
        }, options);
        
        
        // Establish our default settings
        return $("#"+ settings.id).each( function() {
            // bind the entered text
            $(this).text( settings.text );

           //Apply user defined style
            if ( settings.color ) {
                $(this).css( 'color', settings.color );
            }

            // Apply user defined font style
            if ( settings.fontStyle ) {
                $(this).css( 'font-style', settings.fontStyle );
            } 
        });
    }   

}(jQuery));


Step3: Run the index.html page into browser and keep typing text into the text box you can see same value displaying below div.

Demo

You can change the color, font, id etc. according to your needs. You may make use of this simple plugin app and build your own jquery plugin also lot of other functionality can be added into the same. Hope this small article helpful to you. If so don’t forget to like, share or leave your comments below. Keep visiting.

Auto reload page content every 3 sec using JQuery, Ajax & PHP


In my last article I wrote “How to auto resize textarea based on the user input.”. While surfing twitter and facebook recently I just noticed both the giant social networking site repetitively search for new comments/tweets to display into end user. Actually it is pretty simple concept, which can achieve via simple script with around 10 lines of code. I drafted this tutorial long back and today I am posting how to auto reload the part of the page and display the number of tweet counts with a simple steps.

Let us create index.php page and paste below code.


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 

    var auto= $('#tweets'), refreshed_content;	
		refreshed_content = setInterval(function(){
		auto.fadeOut('slow').load("result.php?id="<?php  echo $userid; ?>).fadeIn("slow");}, 
		3000); 										
		console.log(refreshed_content);										 
		return false; 
});
</script>


The above script will call result.php page every 3 seconds and fetch the number of tweet count. We will place the count into the div content.


<div class=”container”>
<div id="tweets"> </div> 
</div>

Now let us create result.php to perform twitter live search and return the tweet count to the index.php page. Paste below piece of code into your result.php to perform live database search. Here i have used user_id to search against database similar case of facebook/twitter.


$userid = (string) (isset($_GET['id'])) ? $_GET['id'] : '';

$link = mysql_connect("localhost", "root", "");
mysql_select_db("twitter", $link);
$sql = "Select * FROM user_tweets where user_id = '$userId' ";
$result = mysql_query($sql, $link);
$num_rows = mysql_num_rows($result);

echo "Total $num_rows new Tweets ";exit;


That’s it. We are done. Simple script does all the magic behind. You can also use modified version this script for live notification system. Hope it helps! Please do like or share if it is helpful to you, and also leave your comments below. Keep visiting.

How to auto resize Textarea based on the input


My previous article was about “MongoDB and PHP tutorial for beginners”. Recently I came across a task to auto resize textarea based on the input. You may know textarea element doesn’t resize automatically as like other html elements, so I need to write a script to update the textarea height based on the content. I have done this using simple script which I would like to share with you.

Source Code:

Step 1:

Download jquery library or Google CDN library link. Include it into your web page.

Step 2:

I have fixed the minimum height to 50px. Paste below code into your html page.



<textarea id=”txtarea” class=”comment”></textarea>
<div id=”hidden-textarea-content” class=”comment hidden”></div>

<style type=”text/css”>
.comment {
    padding:5px;
    width:300px;
    overflow: hidden;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word; 
    min-height:50px;
}
.hidden {
    display:none;    
}
</style>



Step 3:

Now paste below code to make our auto resizing to work.



<script type=”text/javascript”>

$(function(){
 
     var textarea = $(“#txtarea”), 
         clonedTextarea = $(“#hidden-textarea-content”), 
         content = null;

             textarea.on(“keyup focus keypress cut paste change keydown”, function() {
                 
                  content = textarea.val();

                  clonedTextarea.css(“width”, textarea.width());
                  clonedTextarea.html(content);
                  textarea.css(‘height’, clonedTextarea.height() + “px”);           

            });

});
</script>


Step 4:

Finally run the page and you can see when you type content into textarea it's height will automatically change.

View Demo:

For a demo, you may have a look at my jsfiddle. Make sure before hit run before you test.

Conclusion:

You can see this simple script will auto resize your textarea. You can still improve the script and also can make script into plugin. Hope this helps, if so please don’t forget to leave your comments, share and give a small like.
Keep visiting.

MongoDB PHP Tutorial for Beginners


My previous article was about “Dependency Injection in PHP”. Today I would like to write about using MongoDB with PHP. This simple tutorial will help you how to start with popular NoSql database MongoDB and php. MongoDB it stores data as structured json format, which improves application performance and allowing you to write scalable application.

MongoDB and PHP tutorial

Installing MongoDB

Before diving into creating application using PHP and MongoDB let us see install MongoDb in your system. MongoDB runs on most of the platforms. I have provided few step below “how to install MongoDB in Ubuntu (Linux) system”.

Open your terminal and execute below command-



sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list


Now update your local package database by executing below command and install latest stable version of MongoDB.



sudo apt-get update
sudo apt-get install mongodb-org


Here are few useful url for MongoDB installation. For more detail info of linux Installation

http://docs.mongodb.org/manual/administration/install-on-linux/

Windows Installation

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

You can download mongo driver from below link

https://s3.amazonaws.com/drivers.mongodb.org/php/index.html

Unzip the archive and put php_mongo.dll inside your php extension directory and add below line to your php.ini file.


extension=php_mongo.dll


Restart your apache server. That’s it! So we are done with the installation of MongoDB. Let us follow following steps to connect with mongo and do simple crud operations.

Connecting MongoDB with PHP

Connecting MongoDb is very easy and very similar with any other database abstraction class (PDO, Mysqli). By default MongoDb connect with the port 28017. You may access server info by simply entering.

 
http://localhost:28017

Without login credentials.



$mongo = new MongoClient(); or 
$mongo = new Mongo();


With Credentials.



$host = ‘localhost’;
$port = ‘28017’;
$database = ‘test’;
$connecting =  sprintf('mongodb://%s:%d/%s', $host, $port, $database);
$mongo = new Mongo($connecting, array('username'=> $username, 'password'=> $password));

MongoDB default database is “test”. You can create your own database as below.

Selecting Database


$db = $mongo->your_database_name;

Creating Collections or Creating table


$db->createCollection(“products”);
$collection = $db->products;




   $document = array( 
      "name" => "appsntech.com", 
      "description" => "The Technical Blog", 
      "url" => "http://www.appsntech.com/",
      "by", "Sanjoy Dey"
   );

   $collection->insert($document);

Finding document

Find all document from your collections and iterate data to display title.



$collection = $db->products;
$data = $collection->find();

   foreach ($data as $document) {
      echo $document["name"] . "
"; }

Updating Document

Update document with simple update or save method.



$productArray =  array("name"=> "MongoDB");
$product = $collection->findOne($productArray);
$product [‘name’] = ‘MongoDB and PHP Tutorial’;
$product[‘by’] = ‘Sanjoy’;
$product[‘description’] = “Awesome! simple and best tutorial”;
try  {
     $collection->save($product);
} catch (MongoException $e) {
     echo $e->getMessage();
} 


Deleting Document from Collection

Deleting document is as simple as other methods explained above. You can simple delete record from collections with remove method using the key.



$productArray = array( 'name' => 'MongoDB'); // or you can delete by id
 $collection->remove( $productArray, array( 'safe' => true ) );


Conclusion

So finally in this short article we have covered basic CRUD operation using PHP and MongoDB. You can explore much more to build large application. Hope this article helpful to you, if so please don’t forget to leave your comments, share and give a small like.

Keep visiting for latest post.

Diving into the power of Dependency Injection Pattern in PHP


Dependency Injection in PHP


Introduction

In my previous article I shown you "How to build a simple form using Cygnite PHP Framework with Mysql and Angular Js". Today I have an Interesting topic.

Dependency Injection? Sounds Interesting. Yes! Currently it is one of the raising discussion topics among many PHP developers and communities. It is not a new pattern however commonly used in language like java etc. These concepts are mostly used in MVC (Symfony2, Cygnite Framework, Zend2, Laravel etc.) architecture to decouple code. It is because PHP has been adapted to enterprise level and that is why increasing the demand of quality programming with some patterns. If you already know concept of Dependency Injection then you may simply skip the article and visit us back for other latest posts.

Well! What is Dependency Injection?

It is a simple design pattern to create most decoupled software. It makes your code testable, modular and maintainable.

Advantages of Dependency Injection

• Makes your code Testable, maintainable and modular.
• Gives you to flexibility to change dependencies at runtime.
• Allows you building large and scalable projects.

You might have used this pattern unknowingly. So let us see some example how dependency injection are best practice.


class DataGrid
{
    public function render($data)
 {
     ..................
 } 
}

class Application 
{
    private $connection;

    private $session;
 
    public function __construct($session, $host, $username, $password)
    {
          $this->db = new MySqlDatabase($host, $username, $password);
          $this->session = $session; 
    }
 

   public function renderGrid()
   {
          $grid = new DataGrid;
          return $grid->render($this->db->fetchAll());
   } 
}

So in the above example we can see Foo class is dependent on MysqlDatabase class which is hard coded and tightly coupled with each other. Many people says above code is good but if you closely have a look above code has many problem. It uses S.O.L.I.D principle.

What If you want to use some other database class, may be Oracle or any other in future?

What if you want to access extra parameter inside your MysqlDatabase class?

Why to avoid above code?

• Let’s image if we have added extra parameter to MysqlDatabase class, then we need to modify each and every class where MysqlDatabase object created.
• Doing unit testing is hard because all classes are tightly coupled.

How to solve this issue?

Dependency Injection is the solution. There are different types of Injection you can take the advantage of.

• Constructor Injection.
• Setter or Property Injection.
• Interface Injection etc.

Let us rewrite the above code with DI pattern



class Application 
{
    private $connection;
   
    private $grid;

    private $session;
 
    public function __construct($session, MySqlDatabase $database, DataGrid $grid)
    {
          $this->db =  $database;
          $this->session = $session;
          $this->grid = $grid;  
    } 

   public function renderGrid()
   {
          return $this->grid->render($this->db->fetchAll());
   } 
}

$app = new Application($sessionName, new MysqlDatabase(), new DataGrid());
$app->renderGrid();


You can see in the above example we have reduced the complexity and improved it by decoupling it. We have done constructor injection with Type Hinting. It is easy to do unit test now for each class.

You also inject dependencie using property injection or Interface injection. You may have a look at Cygnite Framework DI container, it resolves controller dependencies without any configuration.

Over using DI pattern into your code may lead you to messy code.

When to use Dependency Injection?

Actually it is not when to use Dependency Injection, you can use it for writing more clean code. However Dependency Injection is most preferable in long term projects. It attracts the best developers to follow your code.

Open Source Dependency Injection Frameworks

These days DI became very popular to PHP developers and many framework uses DI container to resolve Dependencies of your Controller class. Some of them are listed below-

Symfony2 Container based on Java Spring.
Cygnite Framework DI Container.
Zend2 DI.
Laravel IoC etc.

Conclusion

So at the end I will say use the pattern wherever applicable, it should not overkill your smaller project. Hope the above article is useful to you and if you have any real time stories to share about Dependency Injection please don't forget to leave a comment below, also give a small like or share. Keep visiting for latest posts.

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 appsntech.com. All rights reserved. Powered By- Sanjoy Dey Productions