cadt-g6 / prepare-for-exam

Let's prepare for the exam, open issue exam here!
0 stars 0 forks source link

Final Web Application (Term 4 ) - Jan 5 2021, 9AM #1

Open theachoem opened 3 years ago

theachoem commented 3 years ago

1. Normal PHP

Comment in PHP:

// This is a single-line comment
# This is also a single-line comment

I. Array

Reference: https://www.php.net/manual/en/language.types.array.php

In PHP, there are three types of arrays:
- Indexed arrays - Arrays with a numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
for (expr1; expr2; expr3)
    statement
    if(condition) break;

example:

/*
 * This is an array with some data we want to modify
 * when running through the for loop.
 */
$people = array(
    array('name' => 'Kalle', 'salt' => 856412),
    array('name' => 'Pierre', 'salt' => 215863)
);

for($i = 0; $i < count($people); ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
/*
 * The above code can be slow, 
 * because the array size is fetched on every iteration.
 */
for($i = 0, $size = count($people); $i < $size; ++$i) {
    $people[$i]['salt'] = mt_rand(000000, 999999);
}
do {
  code to be executed;
} while (condition is true); 
while (condition is true) {
  code to be executed;
} 

There are 2 types of foreach.

foreach (iterable_expression as $value)
    statement

foreach (iterable_expression as $key => $value)
    statement

example:

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
// without an unset($value),
// $value is still a reference to the last item: $arr[3]

foreach ($arr as $key => $value) {
    // $arr[3] will be updated with each value from $arr...
    echo "{$key} => {$value} ";
    print_r($arr);
}
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
theachoem commented 3 years ago

2. OOP

class Fruit {
    // Properties
    public $name;
    // Method
    function set_name($name) {
        $this->name = $name;
    }
}

$banana = new Fruit();
$apple->set_name('Apple');

You can use the instanceof keyword to check if an object belongs to a specific class:

<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit); 
//result: bool(true)
?> 

I. Constructor

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

II. Destructor

function __destruct() {
    echo "The fruit is {$this->name}.";
}

III. Access modifiers

There are three access modifiers:
1. public - the property or method can be accessed from everywhere. This is default
2. protected - the property or method can be accessed within the class and by classes derived from that class
3. private - the property or method can ONLY be accessed within the class

IV. Inheritent

class  Strawberry extends Fruit {
    //statement
}

V. Constant

class Goodbye {
  const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}
echo Goodbye::LEAVING_MESSAGE;

we can access a constant from inside the class by using the self keyword.

class Goodbye {
  const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
  public function byebye() {
    echo self::LEAVING_MESSAGE;
  }
}

$goodbye = new Goodbye();
$goodbye->byebye();

VI. Abstract class

// Parent class
abstract class Car {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  abstract public function intro() : string;
}

VII. Child classes

class Audi extends Car {
  public function intro() : string {
    return "Choose German quality! I'm an $this->name!";
  }
}

VIII. Interface

interface Animal {
  public function makeSound();
}
class Cat implements Animal {
  public function makeSound() {
    echo "Meow";
  }
}
$animal = new Cat();
$animal->makeSound();
Interface are similar to abstract classes. The difference between interfaces and abstract classes are:
- Interfaces cannot have properties, while abstract classes can
- All interface methods must be public, while abstract class methods is public or protected
- All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary
- Classes can implement an interface while inheriting from another class at the same time

IX. Trait

//usage $table = new Html\Table() //or use Html as H; $table = new H\Table() //or use Html\Table as T; $table = new T();


- [Iterable](https://www.w3schools.com/php/php_iterables.asp)
theachoem commented 3 years ago

3. Git

I. Frequently use git command.

- git config
- git init
- git clone
- git add
- git commit
- git diff
- git reset
- git status
- git rm
- git log
- git show
- git tag
- git branch
- git checkout
- git merge
- git remote
- git push
- git pull
- git stash

II. Add file code to git

$ git init
$ git status
$ git add .
$ git commit -m "First commit"

III. To configure Git user

$ git config --global user.name theacheng
$ git config user.name //theacheng
$ git config --global user.email theacheng.g6@gmail.com
$ git config user.email //theacheng.g6@gmail.com

IV. To host code

$ git init
$ git remote add origin https://github.com/theacheng/profile_templete.git
$ git add .
$ git commit -m "commit message"
$ git pull origin master //pull last update code
$ git push origin master

V. To download code from GitHub

$ git clone https://github.com/theacheng/profile_templete.git
theachoem commented 3 years ago

4. Composer

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. — Composer Introduction.

Reference: https://code.tutsplus.com Official docs here: https://getcomposer.org/doc/03-cli.md#init

$ composer require phpmailer/phpmailer

To use install, you need to create composer.json, or just run: composer init. In the composer.json file, you just need to declare your project dependencies, as shown in the following snippet.

{
    "require": {
        "phpmailer/phpmailer": "~6.1"
    }
}

Anyway, the require command will add a package to your composer.json file automatically.

$composer require phpmailer/phpmailer
theachoem commented 3 years ago

5. Laravel

Reference: https://laravel.com/docs/5.1/quickstart#installation

I. Installation:

$ composer create-project laravel/laravel quickstart --prefer-dist

For existing project:

$ composer install
$ php artisan migrate

II. Migration

To generate a migration file:

$ php artisan make:migration create_tasks_table --create=tasks

It will be placed in database/migrations directory.

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTasksTable extends Migration{

     // Run the migrations.
    public function up(){
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    // Reverse the migrations.
    public function down(){
        Schema::drop('tasks');
    }
}

III. Eloquent Models

To generate a model:

php artisan make:model Task

It will be placed in app directory.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Task extends Model {
    //
}

IV. Routing

  1. Stubbing The Routes So, let's stub all of these routes in the app/Http/routes.php file:
    
    <?php
    use App\Task;
    use Illuminate\Http\Request;

V. Display All Tasks

Route::get('/', function () { // });

VI. Add A New Task

Route::post('/task', function (Request $request) { // });

VII. Delete An Existing Task

Route::delete('/task/{id}', function ($id) { // });

### VIII. Displaying A View
```php
Route::get('/', function () {
    return view('tasks');
});

IX. Define layout

resources/views/layouts/app.blade.php.

<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<nav class="navbar navbar-default">
<!-- Navbar Contents -->
</nav>
</div>
@yield('content')
</body>
</html>

X. Define a child view

resources/views/tasks.blade.php.

@extends('layouts.app')
@section('content')
    <div class="panel-body">
        //note that we have add element to show when error here.
        @include('common.errors') 
        <form action="/task" method="POST" class="form-horizontal">
            {{ csrf_field() }}
            <input type="text" name="name" id="task-name">
            <button type="submit" >Add Task</button>
        </form>
    </div>
@endsection
Route::get('/', function () {
    return view('tasks');
});

XI. Validation & Creating The Task

Route::post('/task', function (Request $request) {
    // validation
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);
    if ($validator->fails()) {
        return redirect('/')
            ->withInput()
            ->withErrors($validator);
    }
    // creating the task
    $task = new Task;
    $task->name = $request->name;
    $task->save();
    return redirect('/');
});

In resources/views/common/errors.blade.php

@if (count($errors) > 0)
    <!-- Form Error List -->
    <div class="alert alert-danger">
        <strong>Whoops! Something went wrong!</strong>
        <br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

XII. Displaying Existing Tasks

Route::get('/', function () {
    $tasks = Task::orderBy('created_at', 'asc')->get();

    return view('tasks', [
        'tasks' => $tasks
    ]);
});

tasks.blade.php

@extends('layouts.app')
@section('content')
// Create Task Form
// Current Tasks
@if (count($tasks) > 0)
<div class="panel panel-default">
<div class="panel-heading">
Current Tasks
</div>
<div class="panel-body">
<table class="table table-striped task-table">
// Table Headings
<thead>
<th>Task</th>
<th>&nbsp;</th>
</thead>
//  Table Body
<tbody>
@foreach ($tasks as $task)
<tr>
// Task Name
<td class="table-text">
<div>{{ $task->name }}</div>
</td>
<td>
<form action="/task/{{ $task->id }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete Task</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
@endif
@endsection

method_field('DELETE') will generate to something like this: <input type="hidden" name="_method" value="DELETE">

In route:

Route::delete('/task/{id}', function ($id) {
    Task::findOrFail($id)->delete();

    return redirect('/');
});