Monday 20 February 2017

CREATING CUSTOM WOOCOMMERCE THEMES

WooCommerce is the world’s favourite eCommerce solution giving you complete control to sell anything on a WordPress platform. We’re going to teach you how to create custom WooCommerce Themes and how to edit the existing ones.
If you happened to miss out on our blog post about WooCommerce and it’s core features now’s the time to read it.
Let’s create WooCommerce Themes!

DECLARE WOOCOMMERCE SUPPORT

Before we start to style our WooCommerce Themes we have to declare WooCommerce support in our theme.
If you don’t do this, your users will get a message in the WordPress dashboard which says the theme is not supported with the WooCommerce plugin. This is very important especially if you’re planning on selling your theme.
It’s very simple to disable this message. All you have to do is add this simple code snippet to your themes functions.php file.
add_action( 'after_setup_theme', 'woocommerce_support' );
function woocommerce_support() {
add_theme_support( 'woocommerce' );
}
view rawfunctions.php hosted with ❤ by GitHub

STYLING WOOCOMMERCE THEMES

Now it’s time to style WooCommerce elements and give them a new look. WooCommerce comes with default styles and we’re going to override them with new ones.
Once yo’ve update your WooCommerce plugin, all of your changes will be lost if you edit original files created by WooCommerce. Because of this we’re not going to edit WooCommerce files at all. We have to create new ones to override existing files in the WooCommerce Themes source directory.
We can style WooCommerce Themes in 2 ways. With the first one we create a custom CSS file that overrides original WooCommerce styles. The second way is to style it with a WordPress child theme.
1. CREATE CUSTOM CSS
If you’re going to do minor changes on your WooCommerce Themes then this is the best way to do them.
The first thing you have to do is to create a new .css file called “custom-woocommerce.css”. We usually place this file in the
wp-content/themes/your-theme-name/cssdirectory but you can place it somewhere else if you want / need to – that depends on your theme file structure.
After you’ve created “custom-woocommerce.css” don’t forget to include it in your theme. All you have to do is insert this code snippet to the bottom of your theme function.php file.
function your_theme_woocommerce_scripts() {
wp_enqueue_style( 'custom-woocommerce-style', get_template_directory_uri() . '/css/custom-woocommerce.css' );
}
add_action( 'wp_enqueue_scripts', 'your_theme_woocommerce_scripts' );
view rawfunctions.php hosted with ❤ by GitHub
Now you can add your CSS to this file and it will override the existing WooCommerce styles.
2. CREATE CHILD THEME
The second way to style WooCommerce Themes is with a WordPress child theme.
A child theme is a theme that inherits the functionality and styling of another theme, called the parent theme. Child themes are the recommended way of modifying an existing theme.
We’re not going to write a lot about child themes because there are some awesome resources where you can read more about this topic. WordPress has great documentation where you can find everything you need to know about child themes.
After you create child theme you also have to create a new “custom-woocommerce.css” and override the existing css files with it in your theme.

EDITING TEMPLATES IN WOOCOMMERCE THEMES

We have learned how to style WooCommerce Themes, now it’s time to learn something new – how to edit WooCommerce templates.
The WooCommerce plugin comes with a number of front-end HTML templates. You can find them in
wp-content/plugins/woocommerce/templates.
If there’s an element you want to place somewhere else or maybe remove, then you’ll edit the WooCommerce template where that element was placed.
To edit a template properly once again, we have to create a copy of it and then make the changes.
HOW TO DO THAT?
  1. In your theme directory create a new “woocommerce” directory.
  2. From the wp-content/plugins/woocommerce/templates directory you have to copy the template you want to edit.
  3. After you copy your template go back to the “woocommerce” directory we have recently created. Here you paste the copied template. If the template was copied from a subfolder inside the “templates” directory than you have to create the same directory structure inside the “woocommerce” directory.
  4. Finally you can edit your new template and change its structure.
For example, this is how your directory should look like when you edit price.php.
WooCommerce Themes

CONCLUSION

After you have learned what is WooCommerce and how to use it, you’re ready to create WooCommerce Themes.
Continue to develop your WordPress and WooCommerce Themes knowledge with us with more posts like this one!

Wednesday 8 February 2017

PHP Object Oriented Programming (OOPs)

 Object Oriented is an approach to software development that models application around real world objects such as employees, cars, bank accounts etc.
The three basic components of object orientation are;
  • Object oriented analysis – functionality of the system

  • Object oriented designing – architecture of the system

  • Object oriented programming – implementation of the application

What is UML?

Unified Modeling Language UML is a technique used to design and document object oriented systems.
UML produces a number of documents, but we will look at the class diagram which is very important to object oriented php programming.

Class Diagram Example


PHP Object Oriented Programming (OOPs)

Class Diagram Key

  • The Upper box contains the class name
  • The middle box contains the class variables
  • The lower box contains the class methods
  • The minus (-) sign means private scope
  • The plus (+) sign means public scope
  • The hash (#) sign means protected scope

What is object oriented programming?

OOP is an approach to programming that uses objects to represent real world objects such as employees.
An object is an occurrence of a class.
Let’s illustrate this with an example.
A class is like a stencil used for drawing.
The stencil outlines the shape of the drawing and any special features that it may have.
An object is the drawing that we come up with from the stencil.
In a nutshell, a class defines the properties and methods of a real world object.

Object Oriented Programming Principles

The three major principles of OOP are;
  • Encapsulation – this is concerned with hiding the implementation details and only exposing the methods. The main purpose of encapsulation is to;
    • Reduce software development complexity – by hiding the implementation details and only exposing the operations, using a class becomes easy.
    • Protect the internal state of an object – access to the class variables is via methods such as get and set, this makes the class flexible and easy to maintain.
    • The internal implementation of the class can be changed without worrying about breaking the code that uses the class.
    • Inheritance – this is concerned with the relationship between classes. The relationship takes the form of a parent and child. The child uses the methods defined in the parent class. The main purpose of inheritance is;
      • Re-usability – a number of children can inherit from the same parent. This is very useful when we have to provide common functionality such as adding, updating and deleting data from the database.
      • Polymorphism – this is concerned with having a single form but many different implementation ways. The main purpose of polymorphism is;
        • Simplify maintaining applications and making them more extendable.

PHP and OOP

PHP is an object oriented scripting language; it supports all of the above principles. The above principles are achieved via;
  • Encapsulation - via the use of “get” and “set” methods etc.
  • Inheritance - via the use of extends keyword
  • Polymorphism - via the use of implements keyword
Now that we have the basic knowledge of OOP and how it is supported in PHP, let us look at examples that implement the above principles

Creating a class

The class keyword is used to define a class in PHP. Below are the rules for creating a class in PHP.
  • The class name should start with a letter
  • The class name cannot be a PHP reserved word
  • The class name cannot contain spaces
Let’s say we want to create a class for representing animals.
We will start with identifying the features that are common to all animals.
  • All animals belong to a family such as herbivore, carnival etc.
  • All animals eat food
The diagram below shows the diagram for the animal
PHP Object Oriented Programming (OOPs)
Let’s now code our animal class
<?php

class Animal {

private $family; private $food;

public function __construct($family, $food) {

$this->family = $family;

$this->food = $food;

}

public function get_family() {

return $this->family;

}

public function set_family($family) {

$this->family = $family;

}

public function get_food() {

return $this->food;

}

public function set_food($food) {

$this->food = $food;

}

}

?>
  HERE,
  • “private $family, $food” means the variables cannot be accessed directly outside the class (Encapsulation).
  • “public function __construct($family…)” is the php constructor method. This function is called whenever an instance of the class has been created. In this case, we are setting the family and food.
  • “public function get…()” is the method used to access the family or food value (Encapsulation)
  • “public function set…()” is the method used to set the family or food value (Encapsulation)

Inheritance implementation

We will work with a cow and a lion. Both the cow and lion inherit from the Animal class.
The class diagram below shows the relationships.
PHP Object Oriented Programming (OOPs)
Note the cow inherits from the animal class and defines its own variable and methods too.
Let’s now code the Cow class
<?php

class Cow extends Animal {

private $owner;

public function __construct($family, $food) {

parent::__construct($family, $food);

}

public function set_owner($owner) {

$this->owner = $owner;

}

public function get_owner(){

return $this->owner;

}

}

?>
  Let’s now code the Lion class
<?php

class Lion extends Animal {

public function __construct($family, $food) {

parent::__construct($family, $food);

}

}

?>
  HERE,
  • “class … extends Animal” makes the cow and lion use methods from the Animal class (Inheritance).

Using the classes

The Animal, Cow and Lion classes should all be in the same directory for simplicity’s sake.
Let’s now create the application that uses our classes.
PHP Class Example
<?php

require 'Animal.php';

require 'Cow.php';

require 'Lion.php';

$cow = new Cow('Herbivore', 'Grass');

$lion = new Lion('Canirval', 'Meat');

echo '<b>Cow Object</b> <br>';

echo 'The Cow belongs to the ' . $cow->get_family() . ' family and eats ' . $cow->get_food() . '<br><br>';

echo '<b>Lion Object</b> <br>';

echo 'The Lion belongs to the ' . $lion->get_family() . ' family and eats ' . $lion->get_food();

?>

Testing our application

Let’s now view our application in a web browser
PHP Object Oriented Programming (OOPs)
Fantastic right! Let’s now look at the third principle of OOP, polymorphism.
Let’s say we want to develop an application that connects to different database engines such as MySQL and SQL Server but use the same uniform interface.
We can create an interface that defines the standard methods and an abstract class that implements the common methods.
  • Interface – it is similar to a class. It only defines the methods and parameters.
  • Abstract class – it is a class that cannot be used to create an object directly. Its purpose is to provide partial or whole implementations of common methods.
The class diagram below illustrates the relationship among our abstract class, interface and implementation classes.
PHP Object Oriented Programming (OOPs)
Let’s now create our abstract class
<?php 
abstract class DBCommonMethods { private $host;   
 private $db;    
 private $uid;    
 private $password; public function __construct($host, $db, $uid, $password)
 { 
 $this->host = $host; 
 $this->db = $db; 
 $this->uid = $uid; 
 $this->password = $password; }
 } ?>
  HERE,
  • “abstract class” means the class cannot be used directly to php create object
  • “$host,$db…” are class variables common to all implementations
  • “function __construct(…)” is the php class constructor method that sets the common variables values at initialization
Let’s now create the interface that contains the standard methods which will be implemented differently depending on the database engine.
<?php

interface DBInterface{

public function db_connect();

public function insert($data);

public function read($where);

public function update($where);

public function delete($where);

}

?>
  HERE,
  • “interface” is the keyword for creating interfaces
  • “public function…(…)” are the standard methods that should be implemented
Let’s now create the concrete classes that will extend the DBCommonMethods class and extend the DBInterface interface. MySQLDriver.php
<?php class MySQLDriver extends 
DBCommonMethods implements DBInterface { public function __construct($host, $db, $uid, $password) 
{ 
parent::__construct($host, $db, $uid, $password); } 

public function db_connect() { //connect code goes here } 

public function delete($where) { //delete code goes here } 

public function insert($data) { //insert code goes here } 

public function read($where) { //read code goes here } 

public function update($where) { //update code goes here } 
} ?>
  MSSQLServerDriver.php
<?php 
class MSSQLServerDriver extends 
DBCommonMethods implements DBInterface { public function __construct($host, $db, $uid, $password)
 { 
 parent::__construct($host, $db, $uid, $password); } 
 public function db_connect() { //connect code goes here } 
 public function delete($where) { //delete code goes here }
 public function insert($data) { //insert code goes here }
 public function read($where) { //read code goes here }
 public function update($where) { //update code goes here }
 } ?>
  HERE,
  • “class … extends DBCommonMethods” use the methods in the DBCommonMethods
  • “… implements DBInterface” ensures that the class provides standard methods regardless of the database driver used.
Usage of the above code The code using the above class would look like this
<?php $db = new MySQLDriver($host,$db,$uid,$password); ?>
Or
<?php $db = new MSSQLServerDriver ($host,$db,$uid,$password); ?>
The rest of the code would be the same for both drivers such as;
<?php
$db->db_connect();

$db->insert($data);
?>

Summary

  • Object Oriented Programming OOP is a powerful technical that models applications after real world objects
  • A class is a representation of real world objects with properties and methods
  • The three basic principles of OOP are;
    • Encapsulation
    • Inheritance
    • Polymorphism

Object Oriented Programming in PHP

We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects.

Object Oriented Concepts

Before we go in detail, lets define important terms related to Object Oriented Programming.
  • Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.
  • Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.
  • Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.
  • Member function − These are the function defined inside a class and are used to access object data.
  • Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
  • Parent class − A class that is inherited from by another class. This is also called a base class or super class.
  • Child Class − A class that inherits from another class. This is also called a subclass or derived class.
  • Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
  • Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
  • Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted).
  • Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object.
  • Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class.
  • Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.

Defining PHP Classes

The general form for defining a new class in PHP is as follows −
<?php
   class phpClass {
      var $var1;
      var $var2 = "constant string";
      
      function myfunc ($arg1, $arg2) {
         [..]
      }
      [..]
   }
?>
Here is the description of each line −
  • The special form class, followed by the name of the class that you want to define.
  • A set of braces enclosing any number of variable declarations and function definitions.
  • Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.
  • Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.

Example

Here is an example which defines a class of Books type −
<?php
   class Books {
      /* Member variables */
      var $price;
      var $title;
      
      /* Member functions */
      function setPrice($par){
         $this->price = $par;
      }
      
      function getPrice(){
         echo $this->price ."<br/>";
      }
      
      function setTitle($par){
         $this->title = $par;
      }
      
      function getTitle(){
         echo $this->title ." <br/>";
      }
   }
?>
The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Here we have created three objects and these objects are independent of each other and they will have their existence separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling member functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example −
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce the following result −
Physics for High School
Advanced Chemistry
Algebra
10
15
7

Constructor Functions

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.
PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.
function __construct( $par1, $par2 ) {
   $this->title = $par1;
   $this->price = $par2;
}
Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below −
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce the following result −
  Physics for High School
  Advanced Chemistry
  Algebra
  10
  15
  7

Destructor

Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor.

Inheritance

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows −
class Child extends Parent {
   <definition body>
}
The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics −
  • Automatically has all the member variable declarations of the parent class.
  • Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the requirement.
class Novel extends Books {
   var $publisher;
   
   function setPublisher($par){
      $this->publisher = $par;
   }
   
   function getPublisher(){
      echo $this->publisher. "<br />";
   }
}
Now apart from inherited functions, class Novel keeps two additional member functions.

Function Overriding

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.
In the following example getPrice and getTitle functions are overridden to return some values.
function getPrice() {
   echo $this->price . "<br/>";
   return $this->price;
}
   
function getTitle(){
   echo $this->title . "<br/>";
   return $this->title;
}

Public Members

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations −
  • From outside the class in which it is declared
  • From within the class in which it is declared
  • From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected.

Private members

By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.
A class member can be made private by using private keyword infront of the member.
class MyClass {
   private $car = "skoda";
   $driver = "SRK";
   
   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   
   function myPublicFunction() {
      return("I'm visible!");
   }
   
   private function myPrivateFunction() {
      return("I'm  not visible outside!");
   }
}
When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private.

Protected members

A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member.
Here is different version of MyClass −
class MyClass {
   protected $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   
   function myPublicFunction() {
      return("I'm visible!");
   }
   
   protected function myPrivateFunction() {
      return("I'm  visible in child class!");
   }
}

Interfaces

Interfaces are defined to provide a common function names to the implementers. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeletons which are implemented by developers.
As of PHP5, it is possible to define an interface, like this −
interface Mail {
   public function sendMail();
}
Then, if another class implemented that interface, like this −
class Report implements Mail {
   // sendMail() Definition goes here
}

Constants

A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of MyClass −
class MyClass {
   const requiredMargin = 1.7;
   
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
}
In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a leading $, as variable names do.

Abstract Classes

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this −
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility.
abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}
Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class.

Static Keyword

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
Try out following example −
<?php
   class Foo {
      public static $my_static = 'foo';
      
      public function staticValue() {
         return self::$my_static;
      }
   }
 
   print Foo::$my_static . "\n";
   $foo = new Foo();
   
   print $foo->staticValue() . "\n";
?> 

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
<?php

   class BaseClass {
      public function test() {
         echo "BaseClass::test() called<br>";
      }
      
      final public function moreTesting() {
         echo "BaseClass::moreTesting() called<br>";
      }
   }
   
   class ChildClass extends BaseClass {
      public function moreTesting() {
         echo "ChildClass::moreTesting() called<br>";
      }
   }
?>

Calling parent constructors

Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here's a simple example −
class Name {
   var $_firstName;
   var $_lastName;
   
   function Name($first_name, $last_name) {
      $this->_firstName = $first_name;
      $this->_lastName = $last_name;
   }
   
   function toString() {
      return($this->_lastName .", " .$this->_firstName);
   }
}
class NameSub1 extends Name {
   var $_middleInitial;
   
   function NameSub1($first_name, $middle_initial, $last_name) {
      Name::Name($first_name, $last_name);
      $this->_middleInitial = $middle_initial;
   }
   
   function toString() {
      return(Name::toString() . " " . $this->_middleInitial);
   }
}
In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an additional field. Similarly, NameSub1 defines its non constructor toString() function in terms of the parent function that it overrides.
NOTE − A constructor can be defined with the same name as the name of a class. It is defined in above example.