Post Top Ad

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Saturday, August 10, 2019

August 10, 2019

PHP Basic in Web Development Course




## Week I

* Introduction to Ubuntu 18.04 
* Ubuntu Basic Command & Basic `GIT` usage
* Install PHP, Web Server, Database MySQL
* Introduction to PHP and Syntax Overview
* PHP Variable Types, Constants
* PHP String
* PHP Array
* PHP If...else...elseif
* PHP Switch
* PHP For Loops
* While Loops
* PHP Function
* Lab 1. Form


> Let's get details : 

###  Introducton to Ubuntu 18.04 LTS

Introducton to Ubuntu 18.04 LTS  [here](https://wiki.ubuntu.com/BionicBeaver/ReleaseNotes)

###  Ubuntu Basic Command

> You can try 10 command line on Ubuntu 18.04 LTS  
1. sudo
This SuperUserDo is the most important command Linux newbies will use. Every single command that needs root’s permission, need this sudo command. You can use `sudo` before each command that requires root permissions –
```bash
    sudo su
```

2. ls (list)
Just like the other, you often want to see anything in your directory. With list command, the terminal will show you all the files and folders of the directory that you’re working in. Let’s say I’m in the `/home` folder and I want to see the directories & files in /home. 
```bash
    /home ls
```

3. cd
​Changing directory (cd) is the main command that always is in use in the terminal. It’s one of the most Linux basic commands. Using this is easy. Just type the name of the folder you want to go in from your current directory. If you want to go up just do it by giving double dots (..) as the parameter.
​
Let’s say I’m in /home directory and I want to move in usr directory which is always in the /home. Here is how I can use `cd` commands –

```bash 
    cd /home/username/Desktop
```

4. mkdir
Just changing directory is still incomplete. Sometimes you want to create a new folder or subfolder. You can use mkdir command to do that. Just give your folder name after mkdir command in your terminal.
```bash
    mkdir folderName
```

5. cp
copy-and-paste is the important task we need to do to organize our files. Using `cp` will help you to copy-and-paste the file from the terminal. First, you determine the file you want to copy and type the destination location to paste the file.
```bash
    cp src des
```

> Note: If you’re copying files into the directory that requires root permission for any new file, then you’ll need to use `sudo` command.  

6. rm
`rm` is a command to remove your file or even your directory. You can use `-f` if the file need root permission to be removed. And also you can use `-r` to do recursive removal to remove your folder.
```bash
    rm myfile.txt
```

7. apt-get
This command differs distro-by-distro. In Debian based Linux distributions, to install, remove and upgrade any package we’ve Advanced Packaging Tool (APT) package manager. The apt-get command will help you install the software you need to run in your Linux. It is a powerful command-line tool which can perform installation, upgrade, and even removing your software.​

```bash
sudo apt-get update
```

8. grep
You need to find a file but you don’t remember its exact location or the path. grep will help you to solve this problem. You can use the grep command to help to find the file based on given keywords.
```bash
    grep user /etc/passwd
```

9. cat
As a user, you often need to view some of text or code from your script. Again, one of the Linux basic commands is cat command. It will show you the text inside your file.
```bash
    cat CMakeLists.txt
```
10. poweroff
And the last one is `poweroff`. Sometimes you need to poweroff directly from your terminal. This command will do the task. Don’t forget to add sudo at the beginning of the command since it needs root permission to execute poweroff.

```bash
    sudo poweroff
```


### Install PHP, Web Server, Database MySQL

1. if you are on Ubuntu. Please follow [here](https://www.rosehosting.com/blog/how-to-install-php-7-3-on-ubuntu-16-04/) 
2. If you are window. Please install [Warm Server](http://www.wampserver.com/en/), [Xampp Server](https://www.apachefriends.org/index.html)

### Introduction to PHP and Syntax Overview

1. Introduction to PHP

`PHP` started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the `first version of PHP` way back in `1994`.
* `PHP` stand for `Hypertext Preprocessor`
* `PHP` is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session, tracking, even build entire e-commerce sites. 
* It is intergrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
* PHP suport a large number of majors protocol such as POP3, IMAP, and LDAP, from `PHP4` added support for Java and distributed ojbect architectures. 

2. Syntax Overview

The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. There are four ways to do this

* Canonical PHP tags
    The most universally effective PHP tag style is: 

    ```bash
        
    ```
* Short-open tags
    Short or short-open tags look like this 
    ```bash
        
    ```
* ASP-Style 
    ASP-style tags mimic the tag used by Active Server Pages to delineate code blocks.

    ```bash
        <% 

        %>
    ```
* HTML script tags
    HTML script tags look like this 
    ```bash
        
    ```

###  PHP Variable Types, Constants

> Here are the most important things to know about variables in PHP.
* All variables in PHP are denoted with a leading dollar sign `$`.
* The value of a variable is the value of its most recent assignment.
* Variables are assigned with the `=` operator, with the variable on the left-hand side and the expression to be evaluated on the right.
* Variables can, but do not need, to be declared before assignment.
* Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters.

* Variables used before they are assigned have default values.

* PHP does a good job of automatically converting types from one to another when necessary.


1. PHP Variable Types

    * Integers: are whole numbers, without a decimal point like 2019.
    * Doubles:  are flaoting-point numbers, like 3.14159, or 201.9.
    * Booleans: have only two possible values either `true` or `false`.
    * NULL: is a special type that only has one value NULL.
    * Strings: are sequences of characters 
    * Array: are nmae and indexed collections of other values.
    * Ojbects: are instances of programmer-defined classes.
    * Resources: are special vairables that hold references to resources external to PHP(such as database connections)

2. PHP Constant 

What is PHP Constant ? 

* A constant is a name or an identifier for a simple value
* A constant value cannot change during the execution of the script
* By default, a constant is case-sensitive
* By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores

```bash

```
* We define constant `MINSIZE` with value 50.
* We print out `MINSIZE` value.
* We use `constant()` function to get value of `MINSIZE`

> Note: Only scalar data (boolean, integer, float and string) can be contained in constants.

### PHP String

> They are sequences of characters, PHP supports string operations.

1. String Concatenation Operator

    To concatenate two string variables together, we us dot(`.`) operators.

    ```bash
        
    ```


2. Get The Length of a String

    The `strlen()` function is used to find the lenght of a string. 
    ```bash
        echo strlen("web development course");
    ```

3. Search For a Specific Text Within a String

    The `strpos()` function is used to search for a string or character with a string.

    ```bash 
    
    ```

4. Count The Number of Words in a String

    PHP `str_word_count()` function is used to count the number of word in a string. 

    ```bash
        
    ```

5. Reverse a String

    The PHP `strrev()` function reverses a string. 
    ```bash 
        
    ```
    please try to reverse: `web development course` to `course development web`. 

6. Replace Text Within a String

    The PHP `str_replace()` function replaces some characters with some other characters in string.

    ```bash
        
    ```

### PHP Array

> An array is a special variable, which can hold more than one value at a time.

```bash 
    $cars1 = "Volvo";
    $cars2 = "BMW";
    $cars3 = "Toyota";
```

1. Create an Array in PHP

    In PHP, there are three types of arrays:
    
    * Indexed arrays - Arrays with a numeric index
        ```bash 
            $cars = array("Volvo", "BMW", "Toyota");
        ```
        The index can be assigned automatically.  the index can be assigned manually:
        ```bash
            $cars[0] = "Volvo";
            $cars[1] = "BMW";
            $cars[2] = "Toyota";
        ```

    * Associative arrays - Arrays with named keys
        ```bash
            $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
        ```
        or 
        ```bash 
            $age['Peter'] = "35";
            $age['Ben'] = "37";
            $age['Joe'] = "43";
        ```
        Associative arrays are arrays that use named keys that you assign to them.
        


    * Multidimensional arrays - Arrays containing one or more arrays

### PHP IF else elseif 

1. PHP IF Else Statment

    In if  Statements Output will appear when only Condition must be true.
    > If Statement works  much like the English language statement, “if X happens, then do Y.”

```bash
    if (condition)
        code to be executed if condition is true;
    else
        code to be executed if condition is false;
```
> let check example:

```bash
    
    
    
        
    
    
    
```

> Exercise 1. Write a PHP program to check whether the given number is a `negative` or `positive` number.   

> Exercise 2. Write a PHP program to check whether the given number is a `odd` or `even` number. 


2. The ElseIf Statement

If you want to execute one code of the several condtion are true. We use `elseif` statment

> Syntax 

```bash

    if (condition)
         code to be executed if condition is true;
    else if (condition)
         code to be executed if condition is true;
    else
        code to be executed if condition is false;

```


### PHP Switch 

If you want to select one of many blocks of code to be executed

```bash 


```

> We can use default switch case statement. By use keyword : `default`

### PHP For Loop

> In `for loop` specified condition is predifined. 

```bash
    for (initialization; condition; increment){
        code to be executed;
    }
```

Example : 
```bash
    
    
        
        
    
    
    
```

### PHP While Loop

> `while loop` executes the statement while the specific condition is true. 

```bash
    while (condition) {
        code to be executed;
    }
```  

Example: 

```bash
    
    
    
        
        
    
    

```


### do-while 

> `do-while loop` execute the statement then check the condition, it mean if the condition is false in that case `one time` statement execute. 

```bash
    do {
        code to be executed;
    } while (condition);
```

Example: 

```bash
    html>
    
      
    
``` ### PHP Function > Function are self contained block of statement which used to perform any specific task. ##### Types of Function * System defined function or build in function * User defined function ###### Advantages of Function > A function is created once but used many time from more than one program. > It reduce duplication within a program. ###### How to define Function. A function will be executed by a call to the function. Syntax: ```bash function function_name( ) { code to be executed; } ``` 1. A simple function ```bash ```

Tuesday, January 9, 2018

January 09, 2018

Advanced Object-Oriented Programming in PHP




Object-oriented programming (OOP) is an important technique regardless of the programming language developers use, and PHP is no exception. This article will discuss how to develop advanced object-oriented programs in PHP.
Image result for php oop advanced

Introduction

PHP is a server-side scripting language used to develop web pages. In the recent times, PHP has become popular because of its simplicity. PHP code can be combined with HTML code and once the PHP code is executed, the web server sends the resulting content in the form of HTML or images that can be interpreted by the browser. We all know the power and importance of object-oriented programming or OOP. This is a technique that is widely used in the modern programming languages.

Common OOP Concepts Used in PHP

Inheritance – Inheritance is the most important concept of Object-oriented programming used in the most common programming language. Inheritance is based on the principle of parent and child classes. In PHP we achieve inheritance by extending the class. By extending a class, the child class inherits the properties of the parent class and additionally, we can add a few more properties.

Listing 1 – Sample code to show inheritance
class Employee {
 public $firstName = "";
 public $lastName = "";
 public $eCode = "";
 public $dept = "";
 
 public function dailyCommonTask() {
  // Code for routine job
 }
}

class Accountant extends Employee {
 public function processMonthlySalary($eCode) {
  // Code for processing salary
 }
}

In the code snippet above we see that the class Accountant is extending the Employee class. An accountant is an employee first, so he performs the daily common jobs as other employees do. At the same time, it is the Accountant's job to process the salary of other employees.

Public, Private and Protected – As in any object-oriented language, PHP also includes the concept of Public, Private and Protected access modifiers.

      • Public – With having public access the code is visible and can be modified by any code from anywhere.
      • Private – With having private access the code is visible and can be modified from within the class only.
      • Protected – With having protected access the code is visible and can be modified from the same class or any of its child class.

Overloading – The overloading feature enables us to have two methods with the same name but with different parameters. Shown in the following code snippet:

Listing 2 – Sample code to show overloading
class Accountant extends Employee {
 public function processMonthlySalary($eCode) {
  // Code for processing salary
 }
 public function processMonthlySalary($eCode, $variablePayFlag, $variablePercentage) {
  if($variablePayFlag) {
     echo "Please process the salary with variable pay ";
  } else {
     echo " Please process the salary without variable pay ";
  }
 }
}

In the code above, we have two methods with the same name ('processMonthlySalary'). In an organization, not all the employees will have the variable pay component in their salary. Hence the accountant will have to process the salary using two different approaches:

      • With variable pay
      • Without variable pay

While processing the salary with variable pay, the accountant needs to mention the amount of the variable pay component.

Note of clarification added to original article post date:
In the above example, we explained the general concept of method overloading. But during actual implementation, we need a PHP function called func_get_args () to handle multiple method signature (having same method name) with different arguments. The func_get_args ()is used inside a PHP function which holds all the arguments (as an array) passed into it. So the same function can be called with different arguments.

For example, let us take a function called myTestFunction () and we want to use it as an overloaded function.

function myTestFunction() 
{
    print_r(func_get_args());
}

Now, multiple calls to this function could be as shown below. The func_get_args ()will have all the arguments which can be used as per requirement. The first call does not pass any argument, the second call passes one argument and the third one sends two arguments. So the function is acting as an overloaded function.

myTestFunction ();
myTestFunction ("Hello");
myTestFunction ("Hello","Dear"); 

There is also another way of implementing overloading in PHP — by using __call() and __callStatic() methods.

For example, the code snippet below shows the arguments passed into it along with the method name. Here $name is case sensitive. The output will print the method name and the arguments passed into it.

public function __call($name, $arguments)
    {

        echo "We are calling in object context '$name' "
             . implode(', ', $arguments). "\n";
    }

public static function __callStatic($name, $arguments)
    {

        echo "We are calling in static context '$name' "
             . implode(', ', $arguments). "\n";
    } 

Accessors and Mutators – Commonly known as getters and setters, or Accessors and Mutators, are widely used in every programming language. Accessors (or getters) are functions that are used to return or get the value of the class level variables. Mutators (or setters) are functions that are used to set or modify the value of a class level variable. These types of classes are used to transfer the data in a collective way from one layer to another. Let us consider the following example:

Listing 3 – Sample code for Accessors and Mutators
class Employee {
 public $firstName =  "";
 public $lastName = "";
 public $eCode =  "";
 public $dept = "";
  public function getfirstName() {
  return $this->firstName();
 }
 public function setfirstName($firstName) {
  $this->firstName = $firstName;
 }
 public function getlastName() {
  return $this->lastName();
 }
 public function setlastName($lastName) {
  $this->lastName = $lastName;
 }
 public function getECode() {
  return $this->eCode();
 }
 public function setECode($eCode) {
  $this->eCode = $eCode;
 }
 public function getDept() {
  return $this->dept();
 }
 public function setDept($dept) {
  $this->dept = $dept;
 }
}

These types of classes are very helpful when we have to transfer the entire Employee object from one layer to another.

Static – Using a static keyword for both variable and method is a common practice in object-oriented programming. Static means that the variable or the method is available per instance of the class. Static methods or variables are used without creating an instance of the class. In fact, the static variables are not accessible via the instance of the class. While creating static methods you must take care that the $this variable is not allowed within a static method.

Listing 4 – Sample code for static keyword and method
class StaticSample {
    public static $my_static = 'Sample Static variable';
    public function staticValue() {
        return self::$my_static;
    }
 public static function aStaticMethod() {
        echo "This is the Hello message from static method";
    }
}

class StaticShow extends StaticSample {
    public function checkStatic() {
        return parent::$my_static;
    }

 public function checkStaticMethod() {
        return parent::$aStaticMethod;
    }
}

Abstract Class – In PHP, these two features of object-oriented programming are used very frequently. Abstract classes that can't be instantiated rather they can be inherited. The class that inherits an abstract class can also be another abstract class. In PHP we can create an abstract class by using the keyword – 'abstract'.

Listing 5 – Sample code for Abstract Class
abstract class testParentAbstract {
 public function myWrittenFunction() {
  // body of your funciton
 }
}

class testChildAbstract extends testParentAbstract {
 public function myWrittenFunctioninChild() {
  // body of your function
 }
}

In the above example, we can create an instance of the child class – testChildAbstract, but we can't create the instance of the parent class – testParentAbstract. As we see that the child class is extending the parent class, we can use the property of the parent class in the child class. We can also implement an abstract method in our child class as per our need.

Interface – In object-oriented programming, the interface is a collection of definitions of some set of methods in a class. By implementing an interface, we force the class to follow the methods defined in the interface. In PHP, interface is defined as in any other language. First, we need to define the interface using the keyword – 'interface'. When implementing, we just need to mention the 'implements' keyword in the implementing class.

Listing 6 – Sample Code for Interface
interface myIface {
 public function myFunction($name);
}

class myImpl implements myIface {
 public function myFunction($name) {
  // function body
 }
}

Summary

PHP has emerged as one of the most popular languages for web application development. It has been enhanced to support different aspects of programming and of those, the object-oriented features are the most important to understand and implement.

Wednesday, November 15, 2017

November 15, 2017

How to install composer on Window 10

Composer is an application-level package manager for the PHP programming language that provides a standard format for managing dependencies of PHP software and required libraries.


If you run PHP applications on WAMP and if you need to need to install composer to manage dependency of libraries inside your project, you can do so by installing Composer for Windows 10.

Click here for video