Wednesday, April 1, 2020

PHP Class and Object

Like C++ and JavaPHP also supports object oriented programming
1.     Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’.
2.     Class is a programmer-defined data type, which includes local methods and local variables.

3.     Class is a collection of objects. Object has properties and behavior.

Defining PHP Classes

The general form for defining a new class in PHP is as follows −
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 an 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 variables of a related objects 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 the 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 Function is a special type of function that is called automatically whenever an object is created. So we take full advantage of this behavior, by initializing many things through constructor functions.
PHP provides a special function called __construct() (double Underscore) 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 this two-member variable at the time of object creation only. Check the 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 

$this Keyword
If you are following this tutorial from the beginning or you started from the OOPS concepts, you must have noticed the usage of $this in some of the code snippets.
this keyword is used inside a class, generally withing the member functions to access non-static members of a class(variables or functions) for the current object.
Let's take an example to understand the usage of $this.
<?php
    class Person {
        // first name of person
        private $name;
                                         
        // public function to set value for name (setter method)
        public function setName($name) {
            $this->name = $name;
        }
       
        // public function to get value of name (getter method)
        public function getName() {
            return $this->name;
        }
    }
   
    // creating class object
    $john = new Person();
   
    // calling the public function to set fname
    $john->setName("John Wick");
   
    // getting the value of the name variable
    echo "My name is " . $john->getName();

?>

My name is John Wick

In the program above, we have created a private variable in the class with name $name and we have two public methods setName() and getName() to assign a new value to $name variable and to get its value respectively.
Whenever we want to call any variable of the class from inside a member function, we use $this to point to the current object which holds the variable.
We can also use $this to call one a member function of a class inside another member function.
NOTE: If there is any static member function or variable in the class, we cannot refer it using the $this.


Angular Data-Binding

Data-binding is the core concept of Angular and used to define the communication between a component and the DOM. It is a technique to link your data to your view layer. In simple words, you can say that data binding is a communication between your typescript code of your component and your template which the user sees. It makes easy to define interactive applications without worrying about pushing and pulling data. Data binding can be either one-way data binding or two-way data binding.

Angular provides four types of data binding and they are different on the way of data flowing.
  1. String Interpolation
  2. Property Binding
  3. Event Binding
  4. Two-way binding

String interpolation/ Angular Expression
String Interpolation is a one-way data-binding technique which is used to output the data from a TypeScript code to HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
For example:
{{ data }}
String interpolation adds the value of a property from the component:
Syntax:
<li>Name: {{ user.name }}</li>  
<li>Email: {{ user.email }}</li>  


Property Binding
Property Binding is also a one-way data-binding technique. In property binding, we bind a property of a DOM element to a field which is a defined property in our component TypeScript code.
For example:
<img [src]="imgUrl"/>
Syntax:
<input type="email" [value]="user.email">  


Event Binding
In Angular, event binding is used to handle the events raised from the DOM like button click, mouse move etc. When the DOM event happens (eg. click, change, keyup), it calls the specified method in the component. In the following example, the cookBacon() method from the component is called when the button is clicked:
For example:
<button (click)="cookBacon()"></button>  


Two-way Data Binding
We have seen that in one-way data binding any change in the template (view) was not be reflected in the component TypeScript code. To resolve this problem, Angular provides two-way data binding. The two-way binding has a feature to update data from component to view and vice-versa.
In two way data binding, property binding, and event binding are combined together.
Syntax:
[(ngModel)] = "[property of your component]"  


Note: For two way data binding, we have to enable the ngModel directive. It depends upon FormsModule in angular/forms package, so we have to add FormsModule in imports[] array in the AppModule.




Angular CLI | Angular Project Setup


Angular is a front-end framework that is used to create web applications. It uses typescript by default for creating logics and methods for a class but the browser doesn’t know typescript. Here webpack comes in the picture, webpack is used to compile these typescript files to JavaScript. In addition, there are so many configuration files you will need to run an angular project on your computer.


Angular CLI is a tool that does all these things for you in some simple commands. Angular CLI uses webpack behind to do all this process.

Note: Please make sure you have installed node and npm in your system. You can check your node version and npm version by using the following command:

node --version
npm --version


 Steps to Create your first application using angular CLI:
·       Step-1: Install angular cli
npm install - g @angular/cli


·       Step-2: Create new project by this command
Choose yes for routing option and, CSS or SCSS.
ng new myNewApp

·       Step-3: Go to your project directory
cd myNewApp


·       Step-4: Run server and see your application in action
ng serve --o


Introduction to directory structure:
·       e2e It contains the code related to automated testing purpose. For example, if on a certain page you are calling a REST API then what should be the return status code, whether it is acceptable or not etc.
·       node_modules It saves all the dev dependencies (used only at development time) and dependencies (used for development as well as needed in production time), any new dependency when added to project it is automatically saved to this folder.
·      src This directory contains all of our work related to project i.e. creating components, creating services, adding CSS to the respective page, etc.
·      package.json This file stores the information about the libraries added and used in the project with their specified version installed. Whenever a new library is added to the project it’s name and version is added to the dependencies in package.json.


Other files: As a beginner you don’t need these files at this time, don’t bother about that. These all are used for editor configurations and information needed at compile time. The builtin webpack in angular CLI manages all for you.
Inside src folder:
·       index.html This is the entry point for the application, app-root tag is the entry point of the application on this single page application, on this page angular will add or remove the content from the DOM or will add new content to the DOM. Base href=”/” is important for routing purposes.

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>MyNewApp</title>
        <base href="/">
     <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" typw="image/x-icon" href="favison.ico">
    </head>
    <body>
        <app-root></app-root>
    </body>
</html>
·     style.scss This file is the global stylesheet you can add that CSS classes or selectors which are common to many components, for example, you can import custom fonts, import bootstrap.css, etc.
·       assets It contains the js images, fonts, icons and many other files for your project.
Inside app folder:
·       app.module.ts An angular project is a composite of so many other modules in order to create an application you have to create a root module for your application in the hierarchy. This app.module.ts file is that. If you want to add more modules at the root level, you can add.
·   declarations It is the reference of the array to store its components. The app component is the default component that is generated when a project is created. You have to add all your component’s reference to this array to make them available in the project.
·    imports If you want to add any module whether angular or you have to add it to imports array to make them available in the whole project.
·       providers If you will create any service for your application then you will inject it into your project through this provider array. Service injected to a module is available to it and it’s child module in the project hierarchy.
·    bootstrap This has reference to the default component created, i.e., AppComponent
·       app.component.html Edit this file to make changes to the page. You can edit this file as an HTML file. Work directly with div or any other tag used inside body tags, these are components and do not add HTML head body tags.

<h1>
    Hello world
</h1>
 <div>
    <p>
        This is my First Angular app.
    </p>
</div>
·      app.component.spec.ts These are automatically generated files which contain unit tests for source component.
·       app.component.ts You can do the processing of the HTML structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc.
·      app.component.scss Here you can add CSS for your component. You can write scss which further compiled to CSS by a transpiler.

More commands that you will need while working on the project:
ng generate component component_name
ng generate service service_name
ng generate directive directive_name