Change the default template engine in yii2

Yii

Posted on 03 Aug 15 by Vickey

Yii use php as the template engine by default but we can change different template engine for example we can use smarty, twig and others
In this post I will use smarty as the template engine with yii. I am using yii2 and i am working on Ubuntu operating System with xampp. so lets start

1. Go to Yii root directory and you will see a file here name as 'composer.json', open this and search the like given below

  "require": {
  
        "php": ">=5.4.0",
        some code here
        some code here
        some code here
        some code here
        
        
    },

now add the below code
      

  "yiisoft/yii2-smarty": "*"


you should see something like this
    

      "require": {
  
        "php": ">=5.4.0",
        some code here,
        some code here,
        some code here,
        some code here,
        
        "yiisoft/yii2-smarty": "*"
        
    },

now go to directory name as  'config' and open web.php file and search text 'components'   and add the below code
    

    'components' => [
    
    
    
            'view' => [
                'renderers' => [
                        'tpl' => [
                        'class' => 'yii\smarty\ViewRenderer',
                    ],
                ],
            ],


 Now open you terminal and locate in yii root folder
                   

cd /opt/lampp/htdocs/yiiroot

 and update composer

sudo /opt/lampp/bin/php /usr/local/bin/composer update

( in window you need different command   'composer update')
            
after installation complete go to your controller and change your render view name
            
 return $this->render('index.tpl');

 now in your views create a file index.tpl and put your smarty code here and open your webpage you see your new tpl file content
            
            
            
            
            
            
            
            
    
    

How to write ajax responce in window popup

Js

Posted on 15 Jul 15 by Vickey

We have many popup plugins and library for open a popup up with the dynamic content. but we can use widnow popup also, which is browser property. we can open our ajax responce in window popup

function openPopup(){

    $.ajax({
    
        type: "POST",
        url: "url here",
        success: function(response){
	  var win=window.open('about:blank','popup','width=600,height=200')
	  with(win.document)
	  {
	    open();
	    write(response);
	    close();
	  }
        }
    });
}

 

What is function overriding vs overloading in php oops

Object Oriented Programming

Posted on 19 Jun 15 by Vickey

Function Overriding

In the sence of Overriding is to replace parent property in child.In Overriding if we have defined a function in base class and we want to change the
its basic functionality in child class then we can do this and this is called function Overriding for example

class BaseController {
{
    public function dbConnection(){

        $host = "localhost";
        $username = "root";
        $password = "root";
        $connection = new mysqli($host, $username, $password);

    }
}



class UsersController extends BaseController {

    public function dbConnection(){

        $host = "192.168.2.00";
        $username = "root";
        $password = "PASSWORD123";
        $connection = new mysqli($host, $username, $password);

    }
}

as you cann see in base class i have a method dbConnection with code for make database connection but in child class
i have change the host and password for database connection

Function Overloading

In programming the function Overloading means is create two function with same name with different functionality by passing different arguments.
but in php we can not create two function with the same name so if we want to implement overloading in php we can take help of _call function
Here is a simple example of function overloading by using of _call function

class Calculate{

    public function __call($name, $arguments){

        if($name='sum'){

            if(count($arguments) === 2 ){
                return $this->sum1($arguments[0],$arguments[1]);
            }
            if(count($arguments) === 3){
                return $this->sum2($arguments[0], $arguments[1],$arguments[2]);
            }
        }
    }
    public function sum1($a,$b){
        echo $a+$b;
    }

    public function sum2($a,$b,$c){
        echo $a+$b+$c;
    }

}
$obj=new Calculate();
echo $obj->sum(1,2);
echo "
";
echo $obj->sum(1,2,3);

here _call magic function manage the overloading by calling different function on basis of number of arguments

Constructor and Destructor in php

Object Oriented Programming

Posted on 19 Jun 15 by Vickey

Constructor

PHP5 allows us to declare constructor function.A constructor function automaticallly called when an object created.so we use it for any basic functionality which we need to use in the initialization of application for example database connectivity or setting of UI.

Class BaseConnection
{

 public function __construct() {

    $host = "localhost";
    $username = "root";
    $password = "root";
    $connection = new mysqli($host, $username, $password);
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    } 
    echo "Connected successfully";
  }
  
}
$obj=new BaseConnection(); //create object

if we are using inheritance and the base class and child class both have constructors then the paraent's class constructor will not call automatically so for run paraent constructor we need to use " parent::__construct()"

Class Connection extends BaseConnection
{
    public function __construct() {
        parent::__construct();
    }
}
$obj=new Connection(); //create object

Destructor

The Destructor function caled automatically when object destroy so if we want to destroy any variable or other member of a class then we destroy it in __destruct function
for example after complete all database operation we want to cloase database connection

Class BaseConnection
{
    public function __destruct() {
    
    $connection=mysqli_connect("localhost","user","password","db");
    mysqli_close($connection);
      
   }
}

For call parent  __destruct we use parent::__destruct() same as for __construct

Class Connection extends BaseConnection
{
    public function __destruct() {
        parent::__destruct();
    }
}

 

What is use of _get and _set methods in php

Object Oriented Programming

Posted on 18 Jun 15 by Vickey

_get method

_get method called when object try to read an inaccessible or unavailable property. This make a property that is not available.
For example in the class 'User' i have getdetails function in which i have defined 'name' 'email' and 'phone' but not defined 'dob'
so when i create an object and try to access dob then it will show a message that i gave in _get function for this property

class User{

  public function __construct() {
    $this->getdetails();
  }
  public function getdetails() {
    $this->name='vickey';
    $this->email='test@gmail.com';
    $this->phone='123456';
    return $this;
  }


  public function __get($field) {
      return $field.' field not exist';
  }
}
$tux = new User();
echo $tux->name; echo "
";
echo $tux->email; echo "
";
echo $tux->phone; echo "
";
echo $tux->dob; echo "
";

 

_set method

In set method we can set a new value for example in the below code i have email but i have set it by _set method

class User{

  public function __construct() {
    $this->getdetails();
  }
  public function getdetails() {
    $this->name='vickey';
    $this->email='test@gmail.com';
    $this->phone='123456';
    return $this;
  }


  public function __get($field) {
      return $field.' field not exist';
  }

  public function __set($field, $value) {

    if($field == 'email') {
      $this->email = 'We can not show you email';
    }
  }
}
$tux = new User();
echo $tux->name; echo "
";
echo $tux->email; echo "
";
echo $tux->phone; echo "
";
echo $tux->dob; echo "
";

 

How to extract a zip file using php

php

Posted on 17 Jun 15 by Vickey

By using the below code we can extract or unzip a zip file in php

$path_of_zip='testfile.zip';
$unzip = new ZipArchive;
$unzip->open($path_of_zip);
if($unzip->open($path_of_zip))
{
     $unzip->extractTo('/path/extract');
}
$unzip->close();

 

Put your date of birth and calculate age in php

php

Posted on 17 Jun 15 by Vickey

Here i am creating a function for create age.For get age we need to put date of birth in YY-mm-dd form

 

function calculateAge($date)
{

    $y = date('Y');
    $m = date('n');
    $d = date('j');
    list($yr,$mo,$day) = explode('-',$date);
    
    $now = ($y*10000+$m*100+$d);
    $past = ($yr*10000+$mo*100+$day);
    $diff = ($past-$now);
    if ($diff>0) { $age = 0 ; }
    else
    {
    $age = (($y-$yr)-1);
    if (($m>$mo) || (($m>=$mo) && ($d>=$day))) { $age++; }
    }
    return $age; 

}

and now call this function

echo calculateAge('1988-10-21');

 

File upload with image validation in laravel

Laravel

Posted on 02 Jun 15 by Vickey

Laravel provide very easy method to upload a file.So lets create a simple file upload system

Step 1: Create a action in your controller for upload a file (if you did not created it)

public function uploadImage(){

    $this->layout->content = View::make('users.uploadImage');
}

Step 2: Create a uploadImage.blade.php file /view/users/ directory and put the below code

@if($errors->any())
    {{ implode ('', $errors->all('<p><strong>:message</strong></p>'))}}
@endif
{{ Form::open(array('url'=>'/postupload','files' => true))}} 
<table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <th>Photo</th>
            <th> {{ Form::file('photo') }} </th>
        </tr>
        <tr>
            <th></th>
            <th>{{ Form::submit('Submit!',array('class' => 'btn')) }}</th>
        </tr>
</table>
{{ Form::close() }}

Now you form ready now need to create an action for post this form and upload file

Step 3: Create a action in your controller

public function postupload(){

    $userdata = array('image' => Input::get('photo'),);
     $rules = array('image' => 'image');  // validate file type image

     $validator = Validator::make($userdata, $rules);
     if($validator->fails())
    { 
        return Redirect::back()->withInput()->withErrors($validator);
    }
    else{

        $file = Input::file('photo');
        $destinationPath = 'uploads'; // give path of directory where you want to save your files
        $filename = Str::random(20) . '.' . Input::file('photo')->guessExtension();
        $upload_success = Input::file('photo')->move($destinationPath, $filename);
        return Redirect::to('success_page');
    }
}

for validation you can use this also

$rules['image'] = 'mimes:jpg,png,gif,svg,jpeg';

Step 4: Now open your routes.php file and add routes for these two action

Route::get('/uploadImage', 'UserController@uploadImage');

Route::post('/postupload', 'UserController@postupload');

Now you can upload your file

How to hide page numbers from laravel pagination

Laravel

Posted on 02 Jun 15 by Vickey

If you have large datasheet and you are showing pagination for these record on your page then it require more space to show pagination with page numbers.

Genearlly we use the below code

$publishedBlogs = Blogs::where('status', '=', 1)->simplePaginate(15);

it will show all pages numbers with previous and next link but for save our webpage space we can show only previous and next links

$publishedBlogs = Blogs::where('votes', '=', 1)->simplePaginate(15);

and for show page links on view we can use

<?php echo $users->render(); ?>

How to create your own custom module or extension in magento

Magento

Posted on 01 Jun 15 by Vickey

From magento community we can install many extension or module.These module provided by magento connect and from third party developers. By these modules or extension we can solve many difficult task without programming.But if we are working on specific task which is not available on magento community then we need to create our own module with own logic. but for creating own custom module there is need good programming skill and good knowledge of magento structure.

All types of modules located in "/app/code" folder here are three types of module 1.Core: Here are the core functionalites stored which come inbuilt with magento installation 2.Community: These comes from third party developers which are paid and free 3.Local: Here we create our custom module

Lets strat ton create custom module

First go to directory " /app/code/" and create a directory name as "local" if not exist now open local directory and here we will create a new directory which will be the name space of our module for example i am creating it with my name "Vickey" don't use underscore or space in this name. now open namespace directory and create a subdirectory and give a name which will be the module name i am giving name "Hello". now we have namespace "Vickey" and module name "Hello".For use this module property we need to declear the module.

go to "/app/etc/modules" and create a xml file with the name of namespace and module name for example Vickey_Hello.xml

and add the code like this

<?xml version="1.0"?>
<config>
         <modules>
                <Vickey_Hello>
                        <active>true</active>
                        <codePool>local</codePool>
                </Vickey_Hello>
         </modules>
</config>

Now go to directory "/app/code/local/Vickey/Hello" and create a directory "controllers" open this and create a file "IndexController.php" and put the below code in this file

<?php
class Vickey_Hello_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
     $this->loadLayout();
     $this->renderLayout();
    }
}
?>

after creating controller again go to "/app/code/local/Vickey/Hello" create directory Block and create a file "Hello.php" and put code

<?php
class Vickey_Hello_Block_Hello extends Mage_Core_Block_Template
{
  methods
}

?>
create a file "/app/code/local/Vickey/Hello/etc/config.xml" and put code
<?xml version="1.0"?>
<config>
    <global>
        <modules>
                <vickey_hello>
                        <version>0.1.0</version>
                </vickey_hello>
        </modules>

    <blocks>
            <hello>
                <rewrite>
         <hello>Vickey_Hello_Block_Hello</hello>
        </rewrite>
            </hello>
     </blocks>

        </global>
       <frontend>
                <routers>
                        <hello>
                                <use>standard</use>
                                <args>
                                      <module>Vickey_Hello</module>
                                      <frontName>hello</frontName>
                                </args>
                        </hello>
                </routers>
        <layout>
            <updates>
                <hello>
                      <file>hello.xml</file>
                </hello>
            </updates>
            </layout>
        </frontend>
</config>

Now go to your theme which is set for your magento frontend

"/opt/lampp/htdocs/magento/app/design/frontend/my_theme/default/layout" and create a file "hello.xml" and add code

<?xml version="1.0"?>
    <layout version="0.1.0">
        <hello_index_index>
            <reference name="root">
                <action method="setTemplate"><template>page/1column.phtml</template></action>
            </reference>
            <reference name="content">
                <block type="hello/hello" name="hello" template="hello/hello.phtml"/>
            </reference>
        </hello_index_index>
    </layout>

after completing saving this file go to directory "/app/design/frontend/my_theme/default/template" and create a subdirectory "hello" with a file name as hello.phtml and put something which you want to show on webpage and you have done now open your browser put url "your domain name/index.php/hello"

I hope this will help you to creating your first custom module