Instant PHP

2016 Spring Dongyue Web Studio

by ComMouse

(background image by anonymous)

Contents

Why PHP?

What is PHP?


  • PHP: Hypertext Preprocessor
  • Personal Home Page
  • Server-side Scripting Language

Why PHP?

  • Fast
  • Flexible
  • Pragmatic
  • Powerful
  • Easy to learn

THE BEST PROGRAMMING LANGUAGE

Usage of Server-side Programming Languages for Websites

2010
1 Jan
2011
1 Jan
2012
1 Jan
2013
1 Jan
2014
1 Jan
2015
1 Jan
2016
1 Jan
2016
17 Apr
PHP 72.5% 75.3% 77.3% 78.7% 81.6% 82.0% 81.7% 82.3%
ASP.NET 24.4% 23.4% 21.7% 20.2% 18.2% 17.1% 16.0% 15.7%
Java 4.0% 3.8% 4.0% 4.1% 2.7% 2.8% 3.0% 2.7%
static files 1.6% 1.5%
ColdFusion 1.3% 1.2% 1.1% 0.8% 0.7% 0.7% 0.7%
Ruby 0.5% 0.5% 0.6% 0.5% 0.4% 0.6% 0.6% 0.6%
Perl 1.1% 1.0% 0.8% 0.6% 0.5% 0.5% 0.5%
JavaScript <0.1% <0.1% 0.1% 0.1% 0.2% 0.2%
Python 0.3% 0.3% 0.2% 0.2% 0.2% 0.2% 0.2% 0.2%
Erlang 0.1% 0.1% 0.1%
Miva Script             0.1% <0.1%

http://w3techs.com/technologies/history_overview/programming_language/ms/y

Why PHP?

PHP Java Node.js
Environment 5 min 1 hour 5 min
Hello World 10 sec 5 min 1 min
Deploy Just copy files Compile & restart server Copy & restart server

PHP Hello World

hello.php


              hello world
            

Just one line!!

PHP Hello World

hello.php


<?php echo 'hello world'; ?>
            

Still one line with <?php block!!

Set up environment

  • Vagrant / Docker
  • XAMPP
  • PHP CLI Server

Vagrant

See https://github.com/at15/lnmp


vagrant init at15/lnmp
vagrant up --provider virtualbox
            

XAMPP

Bundled with Apache, PHP, MariaDB & phpMyAdmin

Available in Windows, Mac OS X & Linux

See https://www.apachefriends.org/

Form Controls

<input name="username" type="text" placeholder="User Name">
<input name="quantity" type="number" placeholder="Quantity(1-5)" min="1" max="5" step="1">
<input name="password" type="password" placeholder="Password">

Form Controls

Checkbox

Drop List

Text Area

Tips: View Source to find out how these elements work!

What's next?

Make the code more complex :)

How to write unmaintainable PHP code?

POST Form?

Form data are sent not from query string, but where?

Open your developer tool!

POST Form? (Cont.)

quantity[0], quantity[1], quantity[2], quantity[3]?

PHP will parse them as:

  • $_POST['quantity'][0]
  • $_POST['quantity'][1]
  • $_POST['quantity'][2]
  • $_POST['quantity'][3]

Next Challenge

  • Naive Style
  • Procedure Style
  • Functional Style
  • Object Style
  • Meta Style

Inheritance


<?php

class Girl extends Person
{
    private $isMarried = false;

    public function __construct($name, $age, $isMarried = false)
    {
        parent::__construct($name, $age);
        $this->isMarried = $isMarried;
    }

    public function getAgeAfterGrowUp()
    {
        $age = parent::getAgeAfterGrowUp();
        if ($age >= 30) {
            $this->isMarried = true;
        }

        return $age;
    }

    public function fromSJTU()
    {
        return $this->age >= 18 && !$this->isMarried;
    }
}

$girl = new Girl('ayi', 20, false);
var_dump($girl->getAgeAfterGrowUp()); // OK, 21
var_dump($girl->fromSJTU()); // true

Using OOP

We have wrapped the cart into a component class in V4.

v4/src/Dy/Component/Cart.php


<?php
namespace Dy\Component;

/**
 * Class Cart
 * Simple Cart Component
 *
 * @package Dy\Component\Cart
 * @author ComMouse
 */
class Cart
{
    /**
     * Key of cart in $_SESSION
     * @var string
     */
    private $cartKey;

    /**
     * Constructor of the class.
     * This method will be called once an new instance is initialized.
     *
     * @param string $cartKey Key of cart in $_SESSION
     */
    public function __construct($cartKey = 'cart')
    {
        $this->cartKey = $cartKey;
        session_start();
    }

    /**
     * Get the cart from user session.
     * @return array
     */
    public function getItems()
    {
        // Create a new cart if no cart available
        if (!isset($_SESSION[$this->cartKey])) {
            $this->createCart();
        }

        // Return the cart fetched from user session
        return $_SESSION[$this->cartKey];
    }

    /**
     * Set the quantity of the given item in the cart.
     * @param string    $itemName
     * @param int       $quantity   If $quantity <= 0, the item will be removed from the cart.
     */
    public function setItemQuantity($itemName, $quantity)
    {
        if ($quantity <= 0) {
            $this->removeItem($itemName);
            return;
        }

        foreach ($_SESSION[$this->cartKey] as &$item) {
            if ($item['name'] === $itemName) {
                $item['quantity'] = $quantity;
                return;
            }
        }

        // If the item is not found, add it into the cart
        $this->addItem($itemName);
    }

    /**
     * Get the given item in the cart specified by item name.
     * @param  string       $itemName
     * @return array|null   If the item is not found, null will be returned.
     */
    public function getItem($itemName)
    {
        foreach ($_SESSION[$this->cartKey] as $item) {
            if ($item['name'] === $itemName) {
                return $itemName;
            }
        }

        return null;
    }

    /**
     * Add a new item into the cart.
     * @param string $itemName
     */
    public function addItem($itemName)
    {
        if ($this->getItem($itemName) !== null) {
            return;
        }

        $_SESSION[$this->cartKey][] = [
            'name' => (string) $itemName,
            'quantity' => 1
        ];
    }

    /**
     * Remove an item from the cart.
     * @param string $itemName
     */
    public function removeItem($itemName)
    {
        foreach ($_SESSION[$this->cartKey] as $i => $item) {
            if ($item['name'] === $itemName) {
                unset($_SESSION[$this->cartKey][$i]);
                return;
            }
        }
    }

    /**
     * Create an example cart.
     */
    private function createCart()
    {
        $_SESSION['cart'] = [
            ['name' => 'Area A Ticket', 'quantity' => 1],
            ['name' => 'Area B Ticket', 'quantity' => 2],
            ['name' => 'Area C Ticket', 'quantity' => 3],
            ['name' => 'Area D Ticket', 'quantity' => 4]
        ];
    }
}
  

View (Cont.)

Split the logic part & the display part

view/cart.php


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Cart</title>
</head>
<body>
    <h1>My Cart</h1>
    <p>Here is your cart.</p>

    <!-- Cart Info -->
    <form method="POST" action="save_cart.php">
        <ul>
        <?php foreach ($cart->getItems() as $i => $item): ?>
            <li>Name: <?= $item['name'] ?></li>
            <li>Quantity:
                <input name="<?= "quantity[{$item['name']}]" ?>"
                    type="number"
                    value="<?= $item['quantity'] ?>">
            </li>
            <li>
                <a href="<?= 'remove_item.php?name=' . rawurlencode($item['name']) ?>">Remove</a>
            </li>
        <?php endforeach; ?>
        </ul>
        <button>Save</button>
    </form>

    <!-- Add Item Form -->
    <form method="POST" action="add_item.php">
        <h3>Add new item</h3>
        <p>
            <label>Name</label>
            <input name="name" placeholder="Name">
            <button>Add</button>
        </p>
    </form>
</body>
</html>
  

Assignment