"> ">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Outline PHP Introduction and PHP Framework PHP Programming

Similar presentations


Presentation on theme: "Outline PHP Introduction and PHP Framework PHP Programming"— Presentation transcript:

0 Laravel - The PHP Framework For Web Artisans
Chin-Chih Chang/張欽智 Chung Hua University/中華大學資訊工程學系

1 Outline PHP Introduction and PHP Framework PHP Programming
PHP and MySQL Database Laravel Overview Laravel Installation Application Structure and Configuration Lavavel Component Lavavel Database

2 PHP Introduction PHP (Hypertext Preprocessor) is a open source general-purpose scripting language. It is especially suited for web development and can be embedded into HTML. It is originally created by Rasmus Lerdorf in 1994. It is powerful to run large systems such as WordPress, Facebook. Example: <!DOCTYPE html> <html> <body> <?php echo "Hello, this is a PHP script!"; ?> </body> </html>

3 PHP Framework A PHP framework is a collection of classes which facilitate a PHP Web application. Laravel Symfony CodeIgniter yii2 CakePHP Developer(s) Taylor Otwell Symfony Contributors, SensioLabs EllisLab Qiang Xue Michal Tatarynowicz Launched in 2011 2005 2006 2008 Github Stars 35,281 15,252 15,115 10,856 7,261 Download Size 166 KB 7,792 KB 1,395 KB 17,484 KB 1,375 KB PHP Version 5.6.0 MVC framework Yes ORM Third Party DB Migration Plug-in Scaffolding No Yes (CRUD) License MIT New BSD

4 PHP Installation and Testing
Download and install a package suit of Web server, PHP, and DBMS. Xampp is a free, easy to install Apache distribution containing MariaDB, PHP, and Perl. AppServ: WampServer: Download and install Xampp at . Check your server configuration. In xampp\htdocs, create a file phpinfo.php. <?php phpinfo(); ?>

5 Exercise 1: Installing and Testing PHP
Download and install Xampp. In xampp\htdocs, create a file phpinfo.php. Check PHP installation at In xampp\htdocs, create a file hello.php and run it. <?php phpinfo(); ?> <!DOCTYPE html> <html> <body> <?php echo "Hello, World!";?> </body> </html>

6 PHP Programming The PHP processor has two modes: copy (HTML) and interpret (PHP) . PHP syntax is similar to that of JavaScript PHP is dynamically typed and purely interpreted. PHP code can be specified in an HTML document enclosed in <?php ?>: Internally: Externally: include ("myScript.inc") the file can have both PHP and HTML. <?php echo "Hello, Welcome to the world of PHP!"; ?>

7 PHP Introduction PHP has no type declarations.
In PHP keywords, classes, functions, and user-defined functions are NOT case-sensitive. Variable names are case-sensitive. An unassigned (unbound) variable has the value, NULL The unset function sets a variable to NULL The IsSet function is used to determine whether a variable is NULL. PHP has many predefined variables, including the environment variables of the host operating system. phpinfo() can be used to list all predefined variables.

8 PHP Data Types PHP has eight primitive types:
Four scalar types: Boolean, integer, double, and string Two compound types: array and object Two special types: resource and NULL Boolean values are true and false. 0 and "" and "0" are false; others are true. $b = true; Integer or double are similar to other languages. String: String literals are enclosed in single or double quotes. In single quotes, embedded variables are NOT interpolated. In double quotes, embedded variables are interpolated.

9 PHP Operators and Control Statements
$name = "Ariana"; echo "Hello, $name. Welcome to the world of PHP!"; echo 'Hello, $name. Welcome to the world of PHP!'; Arithmetic operators: ++, --, +, -, *, /, % Relational operators: ==, ===, !=, <>, !==, >, <, >=, <= ===: equal and of the same type Logical operators: and, or, xor, !, &&, || Control statements: Selection statements: if, if else, elseif, switch Repetition statements: while, do while, for, foreach break, continue

10 PHP Functions Type conversion and functions User defined function
(int) $sum or intval ($sum) or settype ($sum, "integer") gettype ($sum): return type of a variable ($sum) User defined function A function is defined with the function keyword, followed by a name, followed by parentheses () with parameters. Output functions: print, printf: take one parameter echo: take multiple parameter Math functions: abs, ceil, cos, floor, fmod, is_finite, is_nan, log, max, min, pi, pow, rand, round, sin, sqrt

11 PHP String Operations and Functions
Period for catenation: "Hello, " . $name. Indexing - $str{3} is the fourth character. The String functions chop – remove whitespace from the right end explode - break a string into an array implode - join array elements with a string strlen, strcmp, strpos, strpos, substr, as in C str_replace – replace text within a string trim, ltrim, rtrim – strip whitespace from both, left, right ends strtolower, strtoupper – string to lower case, to upper case

12 PHP Arrays In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index Associative arrays - Arrays with named keys Multidimensional Arrays <?php $pets = array("cat", "dog", "rabbit"); echo "I like " . $pets[0] . ", " . $pets[1] . " and " . $pets[2] . "."; ?> <?php $pet_name = array("cat"=>"Kitty", "dog"=>"Pago", "rabbit"=>"Rabby"); foreach($pet_name as $key=>$value) echo $key . ":" . $value . "</br>"; ?> <?php $score = array(array("Art", 80), array("Music", 90), array("C/C++", 90)); for ($row = 0; $row < 3; $row++) {   for ($col = 0; $col < 2; $col++) echo $score[$row][$col]." "; echo "<br/>"; } ?>

13 PHP Arrays PHP Array functions:
array_keys/array_values : return the keys/values of an array. array_key_exists: check if the given key exists in the array. array_push: push elements onto the end of array array_pop: pop elements off the end of array array_shift: shift elements off the beginning of array array_unshift: put elements to the beginning of array is_array: check if a variable is an array. in_array: check if a value exists in an array sizeof/count: count all elements in an array or object sort/ksort/rsort: sort an array/by key/in reverse order unset: unset a given variable

14 PHP Form Handling Form can use two methods: GET and POST. hello.html
$_GET is an array of variables passed to the current script via the URL parameters. $_POST is an array of variables passed to the current script via the HTTP POST method. hello.html hello.php <html><body> <form action="hello.php" method="post"> Name: <input type="text" name="name"><input type="submit"> </form> </body></html> <html> <body>Hello, <?php echo $_POST["name"]; ?></body> </html>

15 PHP Triangle Example triangle.html triangle-area.php
<html> <body> <form action="triangle-area.php" method="post"> a = <input type="text" name="a" size="5"> b = <input type="text" name="b" size="5"> c = <input type="text" name="c" size="5"> <input type="submit" value="area"/> <input type="reset"/> </form> </body> </html> <?php $a = $_POST["a"]; $b = $_POST["b"]; $c = $_POST["c"]; if ($a + $b > $c && $b + $c > $a && $c + $a > $b) { $s = ($a + $b + $c)/2; $area = sqrt($s * ($s - $a) * ($s - $b) * ($s - $c)); print "area = $area"; } else print "The triangle cannot be formed.\n"; ?>

16 PHP – Calculator Example
<html> <head><title>Calculator</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post"> <input type = "text" name = "a" value="<?php echo isset($_POST['a']) ? $_POST['a'] : '' ?>" size = "3"> <select name = "op"> <option selected = "selected" value = "+">+</option> <option value = "-">-</option> <option value = "*">*</option> <option value = "/">/</option> </select> <input type = "text" name = "b" value="<?php echo isset($_POST['b']) ? $_POST['b'] : '' ?>" size = "3"> <input type ="submit" value = "="/> <?php if (isset($_POST["a"]) && isset($_POST["b"])) { $a = $_POST["a"]; $b = $_POST["b"]; $op = $_POST["op"]; if ($op == "+") $result = $a + $b; if ($op == "-") $result = $a - $b; if ($op == "*") $result = $a * $b; if ($op == "/") $result = $a / $b; echo $result; } ?> </form> </body> </html>

17 PHP – Guess Number Example
<!DOCTYPE html> <head> <title>Calculator</title> </head> <body> <form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post"> Guess a number (1-10): <input type = "text" name = "guess"/> <input type = "submit" value = "Guess" /> <br/> <?php if (!isset($_POST["number"])) $number = rand() % ; if (isset($_POST["guess"]) && isset($_POST["number"])) { $guess = $_POST["guess"]; $number = $_POST["number"]; if ($number == $guess) print "Excellent! You guessed the correct number, $number!"; elseif ($guess < $number) print "Higher than $guess. Try again!"; elseif ($guess > $number) print "Lower than $guess. Try again!"; } ?> <input type = "hidden" name = "number" value = "<?php echo $number; ?>" /> </form> <label id="result"></p> </body> </html>

18 Exercise 2: HTML and PHP Download and install Notepad++:
Download and exercise samples at Exercise: Create a Web page in which an user input a quadratic equation ax2 + bx + c = 0 and create a php that finds the roots of the equation. x x = 0 x = 1, x = 2 1 -3 2 Solve

19 MySQL Database Example
Create a MySQL database. Click Admin of MySQL.

20 MySQL – Database Example
Create a database "stock". Create table stock (ticker char(6) primary key, company varchar(40) not null, price decimal);

21 PHP and MySQL Database Connect to MySQL database. <?php
$db = mysql_connect("localhost", "web", "web123"); if (!$db) { print "Error - Could not connect to MySQL"; exit; } // Select the samle database $er = mysql_select_db("stock"); if (!$er) { print "Error - Could not select the web_design database"; ?>

22 PHP and MySQL Database Execute SQL.
Get the number of rows in the result, as well as the first row and the number of fields in the rows $result = mysql_query($query); if (!$result) { print "Error - the query could not be executed"; $error = mysql_error(); print "<p>" . $error . "</p>"; exit; } $num_rows = mysql_num_rows($result); $num_fields = mysql_num_fields($result);

23 PHP and MySQL Database Produce the column labels and Output the values of the fields in the row. print "<tr>"; for ($i = 0; $i < $num_fields; $i++) { $meta = mysql_fetch_field($result); print "<th>" . $meta->name . "</th>"; } print "</tr>"; for ($row_num = 0; $row_num < $num_rows; $row_num++) { $row = mysql_fetch_row($result); print "<tr align = 'center'>"; for ($field_num = 0; $field_num < $num_fields; $field_num++) print "<td> $row[$field_num] </td> "; print "</table>";

24 Laravel Overview What is Laravel? Why use Laravel?
It is the PHP framework for Web artisans. Market share: 43.7% Why use Laravel? Quick and functional core that can be extended Clean and simple routing Effective Object-relational mapping (ORM) and database layer Easy integration with third-party libraries. Active and growing community that can provide quick support and answers Supporting unit tests out of the box Async queue and background jobs for the long running tasks

25 Laravel Installation Two ways of installations:
Laravel Homestead virtual machine: Web Server, PHP, and DBMS Package + Laravel Package Laravel installation requirements: PHP >= 7.0.0 OpenSSL PHP Extension PDO PHP Extension Mbstring PHP Extension Tokenizer PHP Extension XML PHP Extension

26 Laravel Installation Download and install a package suit of Web server, PHP, and DBMS and validate if the system meets Laravel requirements. Dowload and install PHP Composer. Add PHP into the system "path". Download and run Composer.exe. Validate PHP Composer installation. DOS Prompt: composer –v

27 Laravel Installation Installing Laravel
Download the Laravel installer using Composer: DOS Prompt: composer global require "laravel/installer"

28 Laravel Installation Create a fresh Laravel installation
DOS Prompt: laravel new demo Install Laravel on local development server Move to the directory of Laravel installation. Run php artisan serve Open

29 Laravel Installation Set up Virtual Host laravel.itri.org.tw.
Edit C:\xampp\apache\conf\extra\httpd-vhosts.conf and add following lines at the end of the file: # VirtualHost for laravel.itri.org.tw <VirtualHost laravel.itri.org.tw:80> DocumentRoot "C:\xampp\htdocs\laravel\public" ServerAdmin <Directory "C:\xampp\htdocs\laravel"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost>

30 Laravel Installation Set up the alias host laravel.itri.org.tw.
Edit C:\Windows\System32\drivers\etc and add following lines at the end of the file: Create a new Laravel project: DOS Prompt: laravel new laravel Check the Laravel installation: laravel.itri.org.tw. # localhost name resolution is handled within DNS itself. # localhost # :: localhost laravel.itri.org.tw

31 Laravel Installation

32 Exercise 3: Installing Laravel
Follow the instructions to install Laravel. Create a project demo: lavaral new demo In demo run php artisan serve. Open

33 Laravel – Application Structure
The root directory of Laravel contains various folders and files as shown in the right figure. app − This directory contains the core code of the application. bootstrap − This directory contains the application bootstrapping script. config − This directory contains configuration files of application. database − This folder contains your database migration and seeds.

34 Laravel – Application Structure
public This is the application’s document root. It starts the Laravel application. It also contains the assets of the application like JavaScript, CSS, Images, etc. resources − This directory contains raw assets such as the LESS & Sass files, localization and language files, and Templates that are rendered as HTML. storage − This directory contains App storage. test − This directory contains various test cases. vendor − This directory contains composer dependencies

35 Laravel – Application Structure
App directory: Console − All the artisan commands are stored in this directory. Events − This directory stores events. Exceptions − This directory contains exception handler. Http − This directory contains controllers, filters, and requests. Jobs − This directory contains jobs for the application. Listeners − This directory contains the event handler. Policies − This directory contains policies of the application Providers − This directory contains various service providers.

36 Laravel Configuration
Environmental Configuration: .env. Database Configuration The database of your application can be configured from config/database.php file.  APP_NAME=Laravel APP_ENV=local APP_KEY=base64:+BvLY5cSahCAkYVGjI06lKbUrEZUXLk2oZrXHSatra0= APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL= DB_PORT=3306 DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret

37 Laravel - Routing Laravel routing is a mechanism to route your request to appropriate controller. It use REST (Representational State Transfer) syntax. The default route files is defined in routes directory. The routes/web.php file defines routes that are for your web interface. Route::get('/', function () { return view('welcome');}); The routes in routes/api.php are stateless and are assigned the api middleware group. For most applications, you will begin by defining routes in your routes/web.php file.

38 Laravel - Routing Available Router Methods: The router allows you to register routes that respond to any HTTP verb: Route::get($uri, $callback); Route::post($uri, $callback); Route::put($uri, $callback); Route::patch($uri, $callback); Route::delete($uri, $callback); Route::options($uri, $callback);

39 Laravel – Routing Example
htpp://localhost:8000 htpp://localhost:8000/user/John <?php // Root URL will match this method Route::get('/', function () { return view('welcome'); }); // Root URL with or without name will match this method Route::get('/user/{name?}',function($name = 'Ariana Grade'){ echo "Name: ".$name; });

40 Laravel - Views Views contain the HTML served by your application and separate your controller / application logic from your presentation logic. Views are stored in the resources/views directory. A simple view (resources/views/greeting.blade.php) might look something like this: We may return it using the global view helper like so: <html> <body> <h1>Hello, {{ $name }}</h1> </body> </html> Route::get('/', function () { return view('greeting', ['name' => 'James']); });

41 Lavavel - Validation Laravel provides several different approaches to validate your application's incoming data. By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules. Validation Steps: Defining The Routes Creating The Controller Writing The Validation Logic Displaying The Validation Errors

42 Laravel – Controller Instead of defining all of your request handling logic as Closures in route files, you may wish to organize this behavior using Controller classes. Controllers can group related request handling logic into a single class. Controllers are stored in the app/Http/Controllers directory. Example: Now, when a request matches the specified route URI, the show method on the UserController class will be executed. Of course, the route parameters will also be passed to the method. Route::get('user/{id}',

43 Laravel – Request To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller { public function store(Request $request) $name = $request->input('name'); }

44 Laravel - Database Laravel makes interacting with databases extremely simple across a variety of database backends using. raw SQL, the fluent query builder, and the Eloquent ORM. Currently, Laravel supports four databases: MySQL Postgres SQLite SQL Server

45 Lavavel – Eloquent ORM The Eloquent ORM (Object Relational Mapping) included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. Before getting started, be sure to configure a database connection in config/database.php. To get started, creating an Eloquent model is required.

46 Creating a Laravel Application
Laravel applications use the Model-View-Controller (MVC) design pattern. Controllers to handle user requests and retrieve data. Models to interact with the database and retrieve objects’ information Views to render pages An application is invoked as follows: When a user enters a URL of the application, a request is made. A route associated with that URL maps the URL to a controller action. That controller action induces the necessary model. That view generates the final page.

47 Laravel Application – User Login
Database Preparation Create a "stock" database. Create an "users" table. Insert a user with the username and password of your choice. MySQL Database Configuration (Modify .env). Create table users ( id int primary key, username varchar(80), password varchar(80), createDate timestamp ) DB_CONNECTION=mysql DB_HOST= DB_PORT=3306 DB_DATABASE=stock DB_USERNAME=root DB_PASSWORD=

48 Laravel Application – User Login
Model: Create App\User.php. php artisan make:model User --migration View: Create \resources\views\login.blade.php. <!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Fonts --> <link href=" rel="stylesheet" type="text/css"> </head> <body> <form action = "/login" method = "post"> <input type = "hidden" name = "_token" value = "{{ csrf_token() }}" Username: <input type = "text" name = "username"><br/> Password: <input type = "password" name = "password"><br/> <input type = "submit" name = "login" value = "Login"> </body></html>

49 Laravel Application – User Login
Controller: Create app\Http\loginControllers.php. php artisan make:controller loginController Routes: Configure Web interface (Modify routes\web.php). <?php namespace App\Http\Controllers; use DB; use Illuminate\Http\Request; use App\Http\Requests\CreateSongRequest; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; Route::get('/', function () { return view('login');}); Route::post('/login',

50 Laravel Application – User Login
class loginController extends BaseController { public function login(Request $req) { $username = $req->input('username'); $password = $req->input('password'); $checkLogin = DB::table('users')-> where(['username'=>$username, 'password'=>$password])->get(); if (count($checkLogin) > 0) echo "Login Successfull!"; else echo "Login Failed!"; }

51 Laravel Application – Stock Query
Create a Stock model. Model file: app/Stock.php Database migration file: database/migrations: [timestamp]_create_stocks_table.php Modify the above create stocks schema file: Create Stock table > php artisan make:model Stock --migration Schema::create('stocks', function (Blueprint $table) { $table->string('ticker'); $table->string('company'); $table->decimal('price') }); > php artisan migrate

52 Laravel Application – Stock Query
Create a resource controller. Controller file: app/Http/Controllers/StockController.php Modify a resource route. In the routes configuration file — routes/web.php — add the following to define a Stock resource route: This route definition will define all of the routes related to the Stock resource > php artisan make:controller StockController Route::resource('stocks', 'StockController');

53 Laravel Application – Stock Query
Request Type Path Action Route Name GET /stocks index stocks.index /stocks/create create stocks.create POST store stocks.store /stocks/{stock} show stocks.show /stocks/{stock}/edit edit stocks.edit PUT/PATCH update stocks.update DELETE destroy stocks.destroy To show Stock page, in the controller’s show action: Use the Stock model to retrieve the designated Stock object from the database. Load a view for the Show Stock page, and pass it the stock object retrieved from the database.

54 Creating a Laravel Application - View
Create the resources/views/stocks/show.blade.php view file with the following code: <!DOCTYPE html> <html><head> <title>stock {{ $stock->ticker }}</title> </head> <body> <h1>Stock {{ $stock->ticker }}</h1> <ul> <li>Company: {{ $stock->company }}</li> <li>Price: {{ $stock->price }}</li> </ul> </body> </html>

55 Exercise 4: Lavavel Database
Use phpMyAdmin to create a database and a table of your design. Write the PHP script to connect to the database in Lavavel Framework. Test your PHP and database in Lavavel Framework.

56 Topic for next Class Mobile App Development Software Native App
Web App Hybrid of Native and Web App Cross Platform App Online App (App Inventor) Software Native App: Android Studio, eclipse Web App: node.js, ionic, jQuery mobile jQuery, phonegap Hybrid of Native and Web App: Android Studio + phonegap


Download ppt "Outline PHP Introduction and PHP Framework PHP Programming"

Similar presentations


Ads by Google