Showing posts with label objects. Show all posts
Showing posts with label objects. Show all posts

Saturday, 29 May 2021

Php: How to compare two objects?

There are two ways to compare two objects in Php.

 

Using == operator

== operator considers objects to be equal if they satisfy any of the following conditions.

a.   Both references point to the same instance

b.   Instances with matching properties and values.

 

This will return false, if objects are of different type (or) do not have same properties with same values.

 

objects_comparison_demo.php

#!/usr/bin/php

<?php

    class Employee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            $this->id = $id;
            $this->name = $name;
        }
    }

   
    class MyEmployee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            $this->id = $id;
            $this->name = $name;
        }
    }

    $emp1 = new Employee(1, 'Krishna');
    $emp1_reference = $emp1;
    $emp2 = new Employee(1, 'Krishna');
    $emp3 = new Employee(2, 'Shankar');
    $my_emp = new MyEmployee(1, 'Krishna');

    echo '$emp1==$emp1_reference : '. (($emp1==$emp1_reference)?'T':'F') . "\n";
    echo '$emp1==$emp2 : '. (($emp1==$emp2)?'T':'F') . "\n";
    echo '$emp1==$emp3 : '. (($emp1==$emp3)?'T':'F') . "\n";
    echo '$emp1==$my_emp : '. (($emp1==$my_emp)?'T':'F') . "\n";



?>

 

Output

$./objects_comparison_demo.php 

$emp1==$emp1_reference : T
$emp1==$emp2 : T
$emp1==$emp3 : F
$emp1==$my_emp : F

 

Using === operator

=== operator considers objects to be equal if both the references point to the same instance.

 

objects_strict_comparison_demo.php

 

#!/usr/bin/php

<?php

    class Employee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            $this->id = $id;
            $this->name = $name;
        }
    }

   
    class MyEmployee{
        public $id;
        public $name;
        
        public function __construct($id, $name){
            $this->id = $id;
            $this->name = $name;
        }
    }

    $emp1 = new Employee(1, 'Krishna');
    $emp1_reference = $emp1;
    $emp2 = new Employee(1, 'Krishna');
    $emp3 = new Employee(2, 'Shankar');
    $my_emp = new MyEmployee(1, 'Krishna');

    echo '$emp1===$emp1_reference : '. (($emp1===$emp1_reference)?'T':'F') . "\n";
    echo '$emp1===$emp2 : '. (($emp1===$emp2)?'T':'F') . "\n";
    echo '$emp1===$emp3 : '. (($emp1===$emp3)?'T':'F') . "\n";
    echo '$emp1===$my_emp : '. (($emp1===$my_emp)?'T':'F') . "\n";



?>

 

Output

$./objects_strict_comparison_demo.php 

$emp1===$emp1_reference : T
$emp1===$emp2 : F
$emp1===$emp3 : F
$emp1===$my_emp : F

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Thursday, 29 April 2021

Php: Classes and objects

 

Classes are used to group functions and variables in a single unit. Once you define a class, you can instantiate any number of objects from that class.

 

Objects and class in Real World scenario

 

Object

An Object is a real world entity. For example, book, cat, box, bus, keyboard, person, screen, cell phone etc., all are objects.

 

So How can we differentiate objects

1.   Depend on their properties

2.   Depend on their behaviors

 

Differentiating two objects based on their properties

Let’s say, there are two persons A and B, we already discussed, each real time entity is an object. So these two persons are objects.

 

First let’s try to find what are the possible properties for the person object

 

Possible properties of a person

height, weight, colour, Education Qualification, country, address are all come under person properties.

 

Now by comparing these properties we can easily differentiate two persons.

Properties

Person A

Person B

Height

6ft

5.5ft

Weight

75Kg

60Kg

Color

white

Black

Country

India

America

As shown in the above table, both the persons has their own properties, So we can differentiate based on them.

 

Differentiating two objects based on their behaviour

consider the same two persons A and B. will try to figure out possible behaviours for the person object

 

Possible behaviours are

walk, run, swim, eat, sleep, see, hear etc., Now by comparing these behaviors we can easily differentiate two persons. 

Behavior

Person A

Person B

Walk

10km/hr

12km/hr

run

20km/hr

18km/hr

sleep

8 Hrs/day

6Hrs/day

 

Class

In normal terms I call class as a category.

 

All persons come under Human category

cat, lion, Elephant come under Animals Category

 

So a class or category is a group of objects with similar properties and behaviours.

 

Objects and class in Programming Terminology

 

What Is an Object?

An object is a software bundle of related state and behavior. The main advantage of java is you can compare objects in Java with real world objects. So it is very easy to work with objects in Java

 

What Is a Class?

A class is a blueprint or prototype from which objects are created.

 

 

How to define a class?

You can define a class using ‘class’ keyword.

 

Syntax

class ClassName{
    
}

 

As per the convention, class name starts with a capital letter and every first character in subsequent word also a capital letter.

 

Example 1

class Person{
    
}

 

Example 2

class EmployeeInfo{
    
}

 

What are properties and methods?

Variables defined in a class are called properties and functions defined in a class are called methods.

 

How to define properties in a class?

Using ‘var’ keyword, you can define properties in a class. For example, following snippet defines four variables $id, $first_name, $last_name and $age.

 

class Employee{

    var $id;
    var $first_name;
    var $last_name;
    var $age;
    ......
    ......

}

 

What is constructor?

Constructor is used to instantiate an object at the time of creation. You can define a construction using ‘function’ keyword and __construct function.

 

class Employee{
    var $id;
    var $first_name;
    var $last_name;
    var $age;

    function __construct($id, $first_name, $last_name, $age){
        $this->id = $id;
        $this->first_name = $first_name;
        $this->last_name = $last_name;
        $this->age = $age;
    }
    ......
    ......
}

$this is used to refer current instance or object properties.

 

Public and private methods

Within a class, you can define both public and private method. Public methods can be called by an object, whereas private methods are accessible within the class.

 

You can define a public method using ‘public’ keyword.

public function set_age($new_age){
    $this->age = $new_age;
}


You can define a private method using ‘private’ keyword.

private function full_name(){
    return $this->get_first_name() . ',' . $this->get_last_name();
}


How to define an object?

An object is created using new keyword followed by class name and constructor arguments.

 

Example

$emp1 = new Employee(1, 'Krishna', 'Gurram', 31);

 

How to call the methods of an object?

Syntax

$object_name -> method_name(arguments);

 

Example

$emp1->to_string();

 

Find the below working example.

 

 

class_demo_1.php

#!/usr/bin/php

<?php

class Employee{
    var $id;
    var $first_name;
    var $last_name;
    var $age;

    function __construct($id, $first_name, $last_name, $age){
        $this->id = $id;
        $this->first_name = $first_name;
        $this->last_name = $last_name;
        $this->age = $age;
    }

    // Gettter methods
    public function get_id(){
        return $this->id;
    }

    public function get_first_name(){
        return $this->first_name;
    }

    public function get_last_name(){
        return $this->last_name;
    }
    
    public function get_age(){
        return $this->age;
    }

    // Setter methods
    public function set_id($new_id){
        $this->id = $new_id;
    }

    public function set_first_name($new_first_name){
        $this->first_name = $new_first_name;
    }

    public function set_last_name($new_last_name){
        $this->last_name = $new_last_name;
    }

    public function set_age($new_age){
        $this->age = $new_age;
    }

    public function to_string(){
        return $this->get_id() . ', ' . $this->full_name() . ', ' . $this->get_age();
    }

    // private methods
    private function full_name(){
        return $this->get_first_name() . ',' . $this->get_last_name();
    }
}

$emp1 = new Employee(1, 'Krishna', 'Gurram', 31);
$emp2 = new Employee(2, 'Chamu', 'Gurram', 30);

echo"id, name, age\n";
echo $emp1->to_string();
echo "\n";
echo $emp2->to_string();

?>


Output

$./class_demo_1.php 

id, name, age
1, Krishna,Gurram, 31
2, Chamu,Gurram, 30






 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Sunday, 22 March 2020

Swagger Editor: Create reusable response objects

Step 1: Create reusable response components.
components:
  responses:
    403Unauthorized:
      description: User do not have permission to access this API
      content:
        application/json:
          schema:
            type: object
            properties:
              statusCode:
                type: integer
                example: 403
              message:
                type: string
                example: Unauthorized
    500InternalServerError:
      description: Unable to process the request
      content:
        application/json:
          schema:
            type: object
            properties:
              statusCode:
                type: integer
                example: 500
              message:
                type: string
                example: Internal Server Error

Above snippet creates two reusable response components 403Unauthorized: to represent error code 403
500InternalServerError: to represent error code 500.

Step 2: Use the reusable response components defined in step 1 in document.
paths:

  /employees/{employeeId}:
    get:
      parameters: 
      - in: path
        name: employeeId
        required: true
        schema:
          type: integer
          example: 123
      responses:
        200:
          description: Get Specific Employee Details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/employee'
        403:
          $ref: '#/components/responses/403Unauthorized'
        500:
          $ref: '#/components/responses/500InternalServerError'


data.yaml
openapi: 3.0.0
info:
  title: Customer Data Aceess API
  description: API to expose all the CRUD operations on  customers
  contact:
    name: Krishna
    email: krishna123@abc.com
    url: https://self-learning-java-tutorial.blogspot.com/
  version: 1.0.0
paths:

  /employees/{employeeId}:
    get:
      parameters: 
      - in: path
        name: employeeId
        required: true
        schema:
          type: integer
          example: 123
      responses:
        200:
          description: Get Specific Employee Details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/employee'
        403:
          $ref: '#/components/responses/403Unauthorized'
        500:
          $ref: '#/components/responses/500InternalServerError'
          
  /employees:
      post:
        description: Add new employee to the organization
        requestBody:
          content:
            application/json:
              schema:
                type: object
                properties:
                  firstName:
                    type: string
                    example: krishna
                  lastName:
                    type: string
                    example: gurram
        responses:
          201:
            description: New Employee is created
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/employee'
          403:
            $ref: '#/components/responses/403Unauthorized'
          500:
            $ref: '#/components/responses/500InternalServerError'
                  
      get:
        parameters: 
          - in: query
            name: from
            description: Page number to return
            required: true
            schema:
              type: integer
              example: 1
          - in: query
            name: size
            description: Number of elements to return
            required: false
            schema:
              type: integer
              example: 10
              minimum: 10
              maximum: 100
          - in: header
            name: onetime_token
            description: token to be used at the time of login
            required: false
            schema:
              type: string
              example: 08c3372a-9314-49d6-b9dd-ff212c1715a5
        responses:
          200:
            description: List of all the employees in organization
            content:
               application/json:
                  schema:
                    type: array
                    items:
                      $ref: '#/components/schemas/employee'
          403:
            $ref: '#/components/responses/403Unauthorized'
          500:
            $ref: '#/components/responses/500InternalServerError'

components:
  responses:
    403Unauthorized:
      description: User do not have permission to access this API
      content:
        application/json:
          schema:
            type: object
            properties:
              statusCode:
                type: integer
                example: 403
              message:
                type: string
                example: Unauthorized
    500InternalServerError:
      description: Unable to process the request
      content:
        application/json:
          schema:
            type: object
            properties:
              statusCode:
                type: integer
                example: 500
              message:
                type: string
                example: Internal Server Error
  schemas:
    employee:
      type: object
      required: 
        - firstName
        - id
      properties:
        id:
          type: integer
          example: 1234
        firstName:
          type: string
          example: krishna
        lastName:
          type: string
          example: gurram
Add the content of data.yaml to swagger editor, you can see the api definitions with respective response codes in the right side of the window.



Previous                                                    Next                                                    Home

Wednesday, 5 February 2014

Classes and Objects

Before, moving in depth details of Object oriented and java features, will discuss what an object and class is.

Objects and class in Real World scenario

Object
An Object is a real world entity. For example, book, cat, box, bus, keyboard, person, screen, cell phone etc., all are objects.

So How can we differentiate objects
1. Depend on their properties
2. Depend on their behaviors

Differentiating two objects based on their properties
Lets say, there are two persons A and B, we already discussed, each real time entity is an object. So these two persons are objects.

First lets try to find what are the possible properties for the person object

Possible properties for a person
height, weight, color, Education Qualification, country, address are all come under person properties.

Now by comparing these properties we can easily differentiate two persons.
Properties Person A Person B
Height 6ft 5.5ft
Weight 75Kg 60Kg
Color white Black
Country India America
As shown in the above table, both the persons has their own properties, So we can differentiate based on them.

Differentiating two objects based on their behavior
consider the same two persons A and B. will try to figure out possible behaviors for the person object

Possible behaviors are
walk, run, swim, eat, sleep, see, hear etc., Now by comparing these behaviors we can easily differentiate two persons. 
Behavior Person A Person B
Walk 10km/hr 12km/hr
run 20km/hr 18km/hr
sleep 8 Hrs/day 6Hrs/day

Class
In normal terms I call class as a category.

All persons come under Human category
cat, lion, Elephant come under Animals Category

So a class or category is a group of objects with similar properties and behaviors.

Objects and class in Programming Terminology

What Is an Object?
An object is a software bundle of related state and behavior. The main advantage of java is you can compare objects in Java with real world objects. So it is very easy to work with objects in Java

What Is a Class?
A class is a blueprint or prototype from which objects are created.

Documentation Comments                                                 Class Declaration                                                 Home