Thursday 23 August 2018

Python - Creating a Command Line Argument (argparse)


For those who often use the Terminal on Linux or cmd on Windows, they will often come into contact with the Command Line for example

$ cd -h
$ sudo apt-get -h
$ dpkg --help
$ arp -a


With python we can create programs to run on the terminal. Example :

import argparse #module
def server_start (server, port):
    print "Starting% s ... OK"% server
    print "% s port:% s"% (server, port)
    
def db_start (db, port):
    print "Starting% s ... OK"% db
    print "% s port:% s"% (db, port)
def main ():
    
    #create Instance parser
    parser = argparse.ArgumentParser (description = "Program start Server")
    
    parser.add_argument (
        "--server",
        type = str,
        required = True,
        help = "Your Server (apache, nginx etc)"
    )
    
    parser.add_argument (
        "--server_port",
        type = int,
        default = 80,
        help = "Your Server port"
    )
    
    parser.add_argument (
        "- db",
        type = str,
        required = True,
        help = "Your Database (mysql, oracle etc)"
    )
    
    parser.add_argument (
        "--db_port",
        type = int,
        default = 3060,
        help = "Your Database port"
    )
        # make the parser
    args = parser.parse_args ()
        #call function
    server_start (args.server, args.server_port)
    db_start (args.db, args.db_port)
if __name__ == '__main__':
    play ()
when we create a program / parser code, then by default we can use the -h command or --help to display help

$ python parser.py -h
or

$ python parser.py --help
then the output

Server start program
optional arguments:
  -h, --help show this help message and exit
  - server SERVER Your Server (apache, nginx etc)
  --db DB Your Database (mysql, oracle etc)
note that according to the coding code, our Command Line program

requires two arguments, namely - server and - db

If we run the program without any argument

$ python parser.py
then the message will appear as follows

usage: parser.py [-h] --server SERVER --db DB
parser.py: error: --server argument is required
With the code we make as above we require the User to

use the Command line as follows:

$ python parser.py --server = apache --server_port 81 --db mysql --db_port = 3030
or (without using = operator)

$ python parser.py - server apache --server_port 81 --db mysql --db_port 3030


Command Line Argument Details
In general, to make our arguments go in the following ways:

1. Positional Command line argument

   p.add_argument ("input_dir", ...)
   p.add_argument ("input_dir", "output_dir" ...)
   This means that the input_dir argument must be in the first position

   and then output_dir must be in the second position. so we have to

   run terminal like this:

  # $ python example.py {path / to / input} {path / to / output}
  $ python example.py / home / image / original / home / image / copy


2. Optional command line argument

    Because of Optional, we can place our arguments anywhere

    during execution. Therefore Optional Arguments must be added

    "-" or "-" sign

    Example:

$ python parser.py --db = mysql --db_port = 3021 --server = apache --server_port = 81
    note that the position is free (unlike the previous example)

In the example above we also see all the arguments using the "-" mark that actually means the Command length. we can short it by adding an argument marked "-"

parser.add_argument (
        
        "-s",
        "--server",
        type = str,
        required = True,
        help = "Your Server (apache, nginx etc)"
    )
- server can we rename or shorten with -s so the execution can be like this

python parser.py -s = apache --server_port 81 --db mysql --db_port = 3030
It's the same as shortened --help with -h



Parser Attribute
parser.add_argument (
    "--server",
    type = str,
    required = True,
    help = "Your Server (apache, nginx etc)"
)
in the example above type, required, help is an Attribute. Here are the main attributes

which is often used in .add_argument ()

  help

    help is a String that we can use for additional information on an Argument.

    highly recommended to add this attribute to make it easier for users to use

    Command that we make. Can be accessed by default with the -h or --help command

  required

    If we feel an argument is mandatory, it can use this attribute.

    required = True

    if we are set required, then we only use type 2 taitu Optional command line argument

    because the Positional Argument is certainly compulsory.

  type

    type is the data type of the Argument value. the most common are: int, float, str.

    type = str

  action

    Explain what will happen if a particular argument is executed. usually will

    save certain values. Yes

Install Slim Framework and Write Your First "Hello World"


Do you want to create a simple website but do you want to start from scratch or a complex framework? You need to try Slim Framework

Installing Slim Framework would be much easier if we're using Composer.

Create a folder (your project folder) in your Web server (htdocs for apache users). for example, we create "slim". create a new file "composer.json" inside slim and type this:

{
    "require": {
        "slim / slim": "2. *"
    }
}
Open you terminal and make sure its under slim folder for example

root @ AcerXtimeline: / opt / lampp / htdocs / slim #
now type: composer or php install composer.phar install (depending on how you install the composer). If you follow this Composer Install Tutorial, you just need the first option

 root @ AcerXtimeline: / opt / lampp / htdocs / slim # composer install
You 'll see the process

Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing slim / slim (2.4.3)
    Downloading: 100%
Writing lock file
Generating autoload files


Once its done, create index.php and type:

require "vendor / autoload.php";

$ app = new \ Slim \ Slim ();

$ app-> get ("/", function () {

    echo "Hello World";
});

$ app-> run ();


Also edit .htaccess file:

RewriteEngine On
RewriteCond% {REQUEST_FILENAME}! -F
RewriteRule ^ index.php [QSA, L]


so you can now open it in Browser:

http: // localhost / slim


Separating Routes In Node.js Express 4


If you prefer using the Query builder in Laravel instead of Eloquent, I'm on your side: D because I also use the query Builder for most Query activities in my Laravel Application.


Well, usually the Coding default from birth might be: D, when the Insert, Update, Delete query might be something like this


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user

    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)

                                  -> update ($ data);

    if ($ update)

        return Redirect :: to ('user / profile');

     else

        // blablaa ...

}

or like this


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user

    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)

                                  -> update ($ data);

    if (! $ update) {


        // redirect with error

        return Redirect :: to ('user / profile') -> with ('error_update', true);

    

     }

     else

       return Redirect :: to ('user / profile');

}

To Update, Delete uses the query builder in laravel, the return is in the form of Affected rows. so the query above is not right and can cause problems.


We can simply handle this as well


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user


    try {


        DB :: table ('user') -> where ('user_id', Auth :: user () -> id) -> update ($ data);


    } catch (\ Exception $ e) {


        // The log will be stored in STorage / logs / laravel.log

        Log :: error ('Can not process update:'. $ E-> getMessage ());

        // redirect with Error

        return Redirect :: to ('user / profile') -> with ('error_update', true);

   }


   // redirect success

   return Redirect :: to ('user / profile') -> with ('success_update', true);

  

}

with try catch we can determine when our query is successful or not


CMIIW


Tips Error Handling Sederhana Pada Query Builder Laravel

If you prefer using the Query builder in Laravel instead of Eloquent, I'm on your side: D because I also use the query Builder for most Query activities in my Laravel Application.

Well, usually the Coding default from birth might be: D, when the Insert, Update, Delete query might be something like this

public function doUpdate ($ data) {

    $ data = array (
     'name' => $ data ['name'],
     'alamar' => $ data ['alamar']
    );

    // auth :: user () -> id: session logged user
    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)
                                  -> update ($ data);
    if ($ update)
        return Redirect :: to ('user / profile');
     else
        // blablaa ...
}
or like this

public function doUpdate ($ data) {

    $ data = array (
     'name' => $ data ['name'],
     'alamar' => $ data ['alamar']
    );

    // auth :: user () -> id: session logged user
    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)
                                  -> update ($ data);
    if (! $ update) {

        // redirect with error
        return Redirect :: to ('user / profile') -> with ('error_update', true);
   
     }
     else
       return Redirect :: to ('user / profile');
}
To Update, Delete uses the query builder in laravel, the return is in the form of Affected rows. so the query above is not right and can cause problems.

We can simply handle this as well

public function doUpdate ($ data) {

    $ data = array (
     'name' => $ data ['name'],
     'alamar' => $ data ['alamar']
    );

    // auth :: user () -> id: session logged user

    try {

        DB :: table ('user') -> where ('user_id', Auth :: user () -> id) -> update ($ data);

    } catch (\ Exception $ e) {

        // The log will be stored in STorage / logs / laravel.log
        Log :: error ('Can not process update:'. $ E-> getMessage ());
        // redirect with Error
        return Redirect :: to ('user / profile') -> with ('error_update', true);
   }

   // redirect success
   return Redirect :: to ('user / profile') -> with ('success_update', true);
 
}
with try catch we can determine when our query is successful or not

CMIIW

Example of Simple 'Advance Where' Query Builder in Laravel

Laravel tips this time I will give a simple code example for Searching the database using Query Builder in laravel.

For example, we want to Search in a table, say, the 'article' table. there may have been a code like this before

//MyModel.php

public static function getSearch ($ search = null) {
    
    // is_publish: 0 = pending, 1 = published

    $ result = DB :: table ('article')
        -> where ('article.is_publish', '1')
        -> where ('article.title', 'LIKE', '%'. $ search. '%')
        -> orWhere ('article.content', 'LIKE', '%'. $ search. '%')
        -> select ('*')
        -> orderBy ('article.id', 'desc') -> paginate (10);

    return $ result;
}
Query Scenario above is looking for WHERE article has been published (is_publish = 1) AND article title like '% ...%' OR article content like '% ...%'.

SELECT * FROM `article` WHERE` article`. `is_publish` = '1' AND `article '.` Title' LIKE '% search%' OR `article`.` Content` LIKE '% search%' ...

The query above is not an error but it will produce incorrect results where the article that is_publish = 0 also appears. To make it right, we must create a code like the following

public static function getSearch ($ search = null) {
    
    // is_publish: 0 = pending, 1 = published

    $ result = DB :: table ('article')
        -> where ('article.is_publish', '1')
        -> where (function ($ query) use ($ search) {

            $ query-> where ('article.title', 'LIKE', '%'. $ search. '%')
                  -> orWhere ('article.content', 'LIKE', '%'. $ search. '%');
        })
        -> select ('*')
        -> orderBy ('article.id', 'desc') -> paginate (10);

    return $ result;
}
The above code will generate the following Raw query

SELECT * FROM `article` WHERE` article`. `is_publish` = '1' AND (`article`.` Title` LIKE '% search%' OR `article` .`content` LIKE '% search%') .. .
Note that we must use Closure

....
-> where (function ($ query) use ($ search) {

    $ query-> where ('article.title', 'LIKE', '%'. $ search. '%')
           -> orWhere ('article.content', 'LIKE', '%'. $ search. '%');
 })
because we access variables outside the function.

Learn Basic OOP in Python

Completing the Basic Python Series before, this time we will learn OOP in Python. Same As with OOP in other programming languages, OOP is of course we will discuss

Class
Object
Constructor
Method
etc.
Writing (syntax)

class ClassName:
    
        # ....
        # ....
or

Employee class (object):

In python we can make a Class Description / Documentation that we make in String form

Employee class:
    'This Class is for Managing Employees'
    
# access outside Class
print employee .__ doc__

#output: This Class to Manage Employees


Class, Object, Constructor and Method
Consider the following example:

Employee class (object):

    'This class is for Employee data'
    jml_karyawan = 0 #Class variable
    
    #constructor
    def __init __ (self, kid, name, position):
        
        self.kid = kid
        self.name = name
        self. position = position
        Employee.jml_ employee + = 1
    
    # method
    def infoKaryawan (self):
    
        print "New employee enters"
        print "==================="
        print "ID:% s"% self.kid
        print "Name:% s"% self.nama
        print "Position:% s"% self. position


# how to access / use classes / create Objects

obj = Employee ("K001", "Reward", "Technician")
obj.infoKaryawan ()

# Add new employees
obj2 = Employee ("K002", "Nadya", "Accounting")
obj2.infoKaryawan ()

# Show total employees
print "-----------------------------"
print "Total Employees:% d"% Employees.jml_karyawan
The program above the output is

New employee enters
===================
ID: K001
Name: Ganjar
Position: Technician
New employee enters
===================
ID: K002
Name: Nadya
Position: Accounting
-----------------------------
Total Employees: 2

We are operating the one code above

__init__, what is that? __init__ is a constructor. The first method will be executed when we first create an Instance from Class. As in other languages ​​we can add Arguments to __init__. The Instance of Class will be initialized in __init__ and we can call it anywhere in that class.

Self, what is that? self is the Instance Class used to access Instance

  self.kid = kid
  self.name = name
  self. position = position
can also call methods in other methods

def method1 (self, argument):
   print "% s argument"% arg

def method2 ():
    self.method1 ("Argument")
Other programming languages ​​also have self or this. the self parameter is written first in the Argument method

def method (self, arg1, arg2, arg3 ....)


The way to classify Classes is generally the same as other Languages

obj = Employee ("K001", "Reward", "Technician")
obj.infoKaryawan ()


CLass variable? note the variable employee. we can create and define a variable in Class. and can be accessed anywhere either in the Class or outside the Class by Syntax

ClassName.variable_name
# Show total employees
print "-----------------------------"
print "Total Employees:% d"% Employees.jml_karyawan


Keep in mind that Python is not like OOP like other languages. therefore we do not find: private, protected and public. The reasons are many and honestly it is difficult to explain it. what is clear Python makers and developers have agreed that they don't need to add that functionality.

If you study deeper for what purpose, for such spaces, it is suitable for systems like what Python is. Maybe we will know more about the reason.



So brief explanation of OOP Python. there are still many that have not been explained from OOP material in python. But of course it will be discussed in the next OOP Python article.

Tips Login dengan Username atau Email di Laravel


Not infrequently we include Username and Email in the registration form like this

Email:

Username:

Password:

....



then after the user has successfully registered, we usually ask to log in by including the username and password. But not infrequently can include either a Username or Email along with a password like this:


Your Email or Username ..


password ...


Sign in



So the user can log in with his username or email. This simple tip is actually possible in PHP native or in other groups.

Here's the simple way in Laravel



# AuthController.php

public function doLogin () {
 
   $ username = Input :: get ('username');
   $ password = Input :: get ('password');

   $ field = filter_var ($ username, FILTER_VALIDATE_EMAIL)? 'email': 'username';
 
   if (Auth :: attempt (array ($ field => $ username, 'password' => $ password)))
   {
      return Redirect :: intended ();
   }
   else
   {
       return Redirect :: to ('login') -> with ('error', 'Invalid username / email or password')
-> withInput ();
   }


} // end of function
       

The login form is quite normal

<input type = "text" name = "username" placeholder = "Email or username ...">
<input type = "password" name = "password" placeholder = "password ..."


Explanation:

 note the following code:

if (Auth :: attempt (array ($ field => $ username, 'password' => $ password)))


By default Auth :: attempt () requires (normally) 2 input-tan namely username and password. We only need to create a flexible username field.

filter_var ($ username, FILTER_VALIDATE_EMAIL)? 'email': 'username';
with the method above the username field we have created dynamically and automatically checks whether the input is an email or not.



So, this time. Happy coding !!!

Codeigniter Web Optimization Tips [part 3]: Lazy Loading Images


Continuing the series Previously, this time a short tutorial we will discuss optimization techniques Codeigniter-based Website with Lazy Loading Images. Images or images are mandatory elements on every website, but can also be a boomerang for our website because it greatly affects the website's performance in terms of Time Response even from the Search Engine's "glasses".

Previous Series

Tutorial: Codeigniter Web Optimization 3 [Part 2]
Website Optimization with Code Minification [Part 1]
Other articles about PHP & Codeigniter
Today's Search Engines are very demanding that our site must be quickly accessed. And one of the slowest causes of loading is Image. Now the method that is now commonly used by everyone is by Lazy Load images aka Images made asyncronously Loaded after all the other Elements Load all.




Keep in mind, the most important thing is that the picture before we install it on the website must be used first after the need. Suppose we set the size, we compress or reduce the size of the image with available tools such as JpegMini or other tools.

Of all Lazy Load libraries that I have tried, I finally use the library Lazyizes. How to use it quite easily,

Install the library on the site

<body>

...

...

...

<script src = "lazysizes.min.js" async = ""> </ script>

</ body>
Set Attribute class = "lazyload" and data-src = "my_image.jpg" for all the Images that we want

<img data-src = "my_image.jpg" class = "lazyload">
Enough with the above steps without any additional configuration, our image is now Lazy Load and that is what I use on this Blog. If you want an additional configuration, please read in the Repo.

For example in the Demo source code

<div class = "mdl-cell mdl-cell - 8-col mdl-cell - 12-col-mdl-cell tablet - 12-col-phone mdl-grid mobile-cell-container">
    <div class = "mdl-shadow - 2dp mdl-color - white mdl-cell mdl-cell - 12-col art-container-pink">
        <h2 class = "h2-header"> <a href="#" class="link-header"> Latest </a> </ h2>
        <ul class = "mdl-list">
        <? php if (isset ($ latest)) {foreach ($ latest as $ lt) {?>
          <li class = "mdl-list__item mdl-list__item - two-line">
            <a class="card-link" href="<?php echo site_url('read/'. $lt['slug']);?> ">
                <span class = "mdl-list__item-primary-content">
                  <! - Add `lazyload` to the class & data-src =" "->
                  <img class = "mdl-list__item-avatar avatar list-avatar-article lazyload" data-src = "<? php echo $ lt ['img_thumbnail'];?>" alt = "<? php echo $ lt ['title ']?> ">
                  <span> <h2 class = "tile-title"> <? php echo $ lt ['title']?> </ h2> </ span>
                  <span class = "mdl-list__item-sub-title list-sub-title">
                      by <? php echo $ lt ['created_by']?> | <? php echo date ('M, d H: i', strtotime ($ lt ['created_at']));?> | <? php echo $ lt ['pageview']; ?> views
                  </ span>
                </ span>
            </a>
          </ li>
        <? php}}?>
        </ ul>
        <div class = "pagination-container">
            <? php echo $ paging; ?>
        </ div>
    </ div>
</ div>
<! - Right side ->
<div class = "mdl-cell mdl-cell - 4-col mdl-cell - 12-col-mdl-cell tablet - 12-col-phone mobile-cell-container">
<? php $ this-> view ('frontend / widget / right'); ?>
<? php $ this-> view ('frontend / widget / right2'); ?>
</ div>

And it will lazy load the image on the following page



Please download the complete source ci_amp. If you have questions please comment.


For the Live Demo, please check this Blog because you have used the same Lazy Load method. for example, the Author or Category page


Codeigniter: Write / Export to Excel with Spout Library


Previously we discussed how to read a large Excel file with Spout. Now it's time to make how to write or Export from PHP to Excel.

Read: Codeigniter: Read Excel (Large) Files with Spout

Here are the steps

1. Prepare your Codeigniter project folder

2. Download the Library Spout here

3. Copy Paste the Spout Library folder to application / third_party

The Spout structure folder will be like this



If so, create an Export.php Controller

<? php defined ('BASEPATH') OR exit ('No direct script access allowed');
/ **
 * Export to Excel with CI and Spout
 *
 * @author budy k
 *
 * /

// load Spout Library
require_once APPPATH. '/ third_party / spout / src / Spout / Autoloader / autoload.php';

// lets Use the Spout Namespaces
use Box \ Spout \ Writer \ WriterFactory;
use Box \ Spout \ Common \ Type;

Export class extends Publicapi_Controller
{
    public function index ()
    {
        $ writer = WriterFactory :: create (Type :: XLSX);
        // $ writer = WriterFactory :: create (Type :: CSV); // for CSV files
        // $ writer = WriterFactory :: create (Type :: ODS); // for ODS files

        // stream to browser
        $ writer-> openToBrowser ("testing.xlsx");

        $ header = [
            'No SP',
            'SP Date',
            'Payment'
        ];
        $ writer-> addRow ($ header); // add a row at a time

        $ rows =
            ['SP-903923', '2017-11-12', '35'],
            ['SP-6546', '2017-10-29', '7567'],
            ['SP-546546', '2017-08-29', '3453'],
            ['SP-675677', '2017-02-29', '4654'],
            ['SP-324344', '2017-12-29', '9789']
        ];

        $ writer-> addRows ($ rows); // add multiple rows at a time

        $ writer-> close ();

    }
}
For those who use data from the database, please adjust and fill the variable $ rows with data from the database

Run in the browser

http: //localhost/my-project/index.php/export
or

http: // localhost / my-project / export
It's good to use Spout, we just define everything (Headers and Rows) in Array only and Sport will automatically create Columns and rows. Spout is also very good for large data / for example thousands to tens of thousands of rows.

Good luck. Don't forget Share well.

Getting to know Polymorphism and its practice in PHP

Polymorphism is a concept in OOP where Classes are
have different functionality from each other but at the same time apply the same Interface. For those of you who learn OOP in PHP it might be a little confused ... but we will give an example and an easy analogy so you understand.

For example, we have an Android, iPhone, Blackberry ... they each have unique and different ways of working but they also actually have at least 1 function / interface that is the same as for example Vendors. So both Android, iPhone, Blackberry all have the same Vendor ... but whoever the vendor is of course this can be different from each other.

If we write in the Code like this

interface {

   public function vendor ();

}

Android class {

   public function vendor () {/ * samsung * /}

}

class Iphone {

   public function vendor () {/ * Apple * /}

}

class Blackberry {

   public function vendor () {/ * RIM * /}

}
Polymorphism is implemented in OOP with the help of Interface features, Abstract Class and Factory Pattern as a complement. We can choose whether to use Interface or Abstract Class, but we must first understand what Interface and Abstract Class are and when each must be used.

Problem Interface, Abstract Our class will not be discussed here. Friends can Googling themselves.

Understanding of Polymorphism and the example of the above Code has been understood? if we just practice right away.

Polymorphism with Interface

Case study: A campus requires a simple administrative system that can generate / generate a Master Number for its Students, Lecturers and Employees.

At a minimum, there are 2 simple ways for the above case, first, it makes the Conditional Statement function simple or the second one completes with the concept of Polymorphism.

With Conditional Statement we can make it like this

function numberInduk ($ category = '') {

   $ number = '';

   switch ($ category) {
      'student' case:
         $ number = 'MHS'. mt_rand (100, 1000);
         break;
      case 'lecturer':
         $ number = 'DSN'. mt_rand (100, 1000);
         break;
      case 'employee':
        $ number = 'KRY' mt_rand (100, 1000);
        break;
   }

   return $ number;
}

echo numberInduk ('student');
echo numberInduk ('lecturer');
echo numberInduk ('employee');
With a simple function / method as above, the case is correct. The only problem is what happens if we want to add another category or want to change the numbering algorithm for each category?

Of course we will change 1 function or class above ... then it can cause new problems like Bugs etc. So the ideal solution is that we have to refactor the above solution into a more modular solution using Polymorphism.

By using Polymorphism + Interface, we can make it like this.

Administration interface
{
    public function number Main ();
}

class Students implements Administration
{
    protected $ prefix = 'MHS';

    public function numberInduk ()
    {
       return $ this-> prefix. mt_rand (100, 1000);
    }
}

class Lecturer implements Administration
{
    protected $ prefix = 'DSN';

    public function numberInduk ()
    {
       return $ this-> prefix. mt_rand (100, 1000);
    }
}

Employee class implements Administration
{
    protected $ prefix = 'KRY';

    public function numberInduk ()
    {
       return $ this-> prefix. mt_rand (100, 1000);
    }
}

// we continue to make caller functions

Main Number generate function (Administration $ adm) {
   return $ adm-> numberBand ();
}


echo generate Number Number (new Student ());
echo generateNomorInduk (new Lecturer ());
echo generate Number Number (new Employee ());
It appears that Polymorphism makes our applications more modular. In practice ... the above classes will be separated (one class 1 file)

For example to be:


- AdministrasiInterface.php
- Mahasiswa.php
- Dosen.php
- Karyawan.php

That way any changes to the application or in the class become easier without having to interfere with the others

Polymorphism with Abstract Class

With the same case as the example above

Administration abstract class
{
     private $ name;

     public function setName ($ name) {
         $ this-> name = $ name;
     }

     abstract public function numberInduk (); // pay attention ...
}

Student class extends Administration
{
     protected $ prefix = 'MHS';

     public function numberInduk ()
     {
          return $ this-> prefix. mt_rand (100, 1000);
     }
}


// ...

// we continue to make caller functions

Main Number generate function (Administration $ adm) {
     return $ adm-> numberBand ();
}


echo generate Number Number (new Student ());

// ...
Another example: Usually PHP Framework and others use the concept of Polymorphism for the Query Builder


abstract class DB
{
     abstract protected function select ($ table, $ column);
}

Mysql class extends DB
{
    public function select ($ table, $ column)
    {

       // ...
    }

}

Oracle extends DB class
{
    public function select ($ table, $ column)
    {

       // ...
     }

}

// Factory class
Query class
{
     public static function driver ($ driver)
     {
        switch ($ driver) {
           case 'mysql':
             return new Mysql ();
             break;
           case 'oracle':
             return new Oracle ();
             break;
           default:
             return new Mysql ();
             break;
       }
    }
}

// For example the use
$ query = Query :: driver ('mysql'); // replace for example ('oracle')

$ query-> select ('student', array ('id', 'name', 'address'));
The conclusion is that implementing Polymorphism helps our program structure be more modular and easier when there are changes or additions in the future.

If you have questions, please comment below ...