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='Prabhat';
    $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='Prabhat';
    $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 "<br>";
echo $tux->email; echo "<br>";
echo $tux->phone; echo "<br>";
echo $tux->dob; echo "<br>";

 

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

How to get all category of a magento store

Magento

Posted on 01 Jun 15 by Vickey

By using below code we can get all category which is come on level 2 if we remove level filter then it will return all parent category and base category

$categories = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('id')
->addAttributeToSelect('name')
->addAttributeToSelect('urlkey')
->addAttributeToSelect('url')
->addAttributeToFilter('level',2)
->addAttributeToSelect('isactive');

foreach ($categories as $category)
{
        $name = $category->getName();
        $url_path = $category->getUrl();

}

if you want to get child categories of a category then you can use this code

$children = Mage::getModel('catalog/category')->getCategories(10);

here 10 is the parent category id

How to get all existing values of a specific attribute in magento

Magento

Posted on 01 Jun 15 by Vickey

In a project i had a custom attribute name as "company" and i need to add a filter on my search page so that i can search my products by company name so i fetch all existing values used for "company" attribute by these value i created a dropdown to show all values

here is code

$attributeCode = 'company';
$products = Mage::getResourceModel('catalog/product_collection')
        ->addAttributeToFilter($attributeCode, array('notnull' => true))
        ->addAttributeToFilter($attributeCode, array('neq' => ''))
        ->addAttributeToSelect($attributeCode);

$companyList = array_unique($products->getColumnValues($attributeCode));

<select onchange="filterBySupplier();" id="labname" class="" style="margin-left: 25px;">
        <option value="">All Labs</option>
        <?php foreach ($companyList as $value) { ?>
        <option value="<?php echo $value; ?>"><?php echo $value; ?></option>
        <?php }?>
</select>

How to create custom magento theme

Magento

Posted on 29 May 15 by Vickey

If you are new in magento then this blog for you.after install magento you need to change your front end design or theme according to your requirement so that you can give new look to the website.In this blog first we understand the structure of Magento theme. when you go in "app/design/frontend" you will see some default themes directory for example

app/design/frontend/default

app/design/frontend/base

these are the default themes in magento. Now go to "/skin/frontend" directory here you will see the same directory as you see in "app/design/frontend". In "/skin/frontend" directory default css and images are stored

so lets start to create new custom theme

Step 1: got to directory "app/design/frontend" and create a copy of "base" directory and rename it which name you want to give your new theme here i am renaming it to newtheme

Step 2: now open directory "/skin/frontend" and copy "default" directory and rename it with the name of your new theme now you have create your new theme

Step 3: Now login your admin pannel and open system >> Design here you will see a button "Add Design Change" click on it and you will see a form name a "General Settings" select your theme under theme package for example as i am using my custom theme "newtheme" then i will select newtheme >> defualt and save this.now my new theme has been set. But this will look like defualt theme so we need to edit this

Step 4: First go directory "/js" which is located at your magento root folder and put your all js files here.

Step 5: Got to directory "/skin/frontend/newtheme/default" and put your css and images here

Step 6: Now go to "/app/design/frontend/newtheme/default/layout/ and open file page.xml and search "page/html_head" you will see code like thiss

<block type="page/html_head" name="head" as="head">
<action method="addJs"><script>prototype/prototype.js</script></action>
<action method="addJs"><script>lib/ccard.js</script></action>
<action method="addJs"><script>prototype/validation.js</script></action>
<action method="addJs"><script>scriptaculous/builder.js</script></action>
<action method="addJs"><script>scriptaculous/effects.js</script></action>
<action method="addJs"><script>scriptaculous/dragdrop.js</script></action>
<action method="addJs"><script>scriptaculous/controls.js</script></action>
<action method="addJs"><script>scriptaculous/slider.js</script></action>
<action method="addJs"><script>varien/js.js</script></action>
<action method="addJs"><script>varien/form.js</script></action>
<action method="addJs"><script>varien/menu.js</script></action>
<action method="addJs"><script>mage/translate.js</script></action>
<action method="addJs"><script>mage/cookies.js</script></action>

add your js file like this

<action method="addJs"><script>my_new_js_file.js</script></action>

and css like this

<action method="addCss"><stylesheet>css/styles.css</stylesheet></action>

you have set your css and js files and now we will work our html part

Step 7: Go to directory /app/design/frontend/newtheme/default/template/page/html/ and open file "header.phtml" comment old code and put your header ocde here and save

Step 8: Open "footer.phtml" and do same with footer

Step 9: Now open "1column.phtml" and make changes in html according to your design do same for "2columns-left.phtml" , "2columns-right.phtml", "3columns.phtml" if your using these for any page you can set these layout from admin pannel. for change layout go to CMS >> Pages and change your layout for different pages and now open your. when you will refresh your page you will see changes