Bài giảng Phát triển phần mềm nguồn mở - Bài 8: Controllers, request, response, session - Nguyễn Hữu Thể

Controllers

− Controllers có thể nhóm các xử lý request logic vào

một class.

− Thư mục Controllers: app/Http/Controllers

Tạo Controller:

php artisan make:controller --plain

pdf 56 trang phuongnguyen 7020
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Phát triển phần mềm nguồn mở - Bài 8: Controllers, request, response, session - Nguyễn Hữu Thể", để tải tài liệu gốc về máy hãy click vào nút Download ở trên

Tóm tắt nội dung tài liệu: Bài giảng Phát triển phần mềm nguồn mở - Bài 8: Controllers, request, response, session - Nguyễn Hữu Thể

Bài giảng Phát triển phần mềm nguồn mở - Bài 8: Controllers, request, response, session - Nguyễn Hữu Thể
 PHÁT TRIỂN PHẦN MỀM NGUỒN MỞ
CONTROLLERS, REQUEST, RESPONSE, SESSION
 Nguyễn Hữu Thể
 Controllers
− Introduction
− Basic Controllers
 • Defining Controllers
 • Controllers & Namespaces
 • Single Action Controllers
 2
 1 View: nhap.blade.php
 ">
 Name 
<?php 2. Controller: MyController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MyController extends Controller{
 public function postRegister(Request $request){
 $name = $request->input('name');
 echo 'Name: '.$name;
 }
} 
 3. Route:
Route::get ( '/register', function () {
 return view ( ‘nhap' );
} );
Route::post('/user/register’,’MyController@postRegister');
 Controllers
− Controllers có thể nhóm các xử lý request logic vào
 một class.
− Thư mục Controllers: app/Http/Controllers
❖ Tạo Controller:
 php artisan make:controller --plain
 5
 Controllers
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller {
 /**
 * Show the profile for the given user.
 *
 * @param int $id
 * @return Response
 */
 public function show($id) {
 return view('user.profile', ['user' => 
 User::findOrFail($id)]);
 }
}
 6
 Controllers
▪ Định nghĩa một route cho action của controller
 Route::get('user/{id}', 'UserController@show');
▪ Khi request với route URI, phương thức show của class 
 UserController sẽ được thực thi. 
 7
 Action Controllers
__invoke(): Định nghĩa một controller xử lý duy nhất một action
 namespace App\Http\Controllers;
 use App\User;
 use App\Http\Controllers\Controller;
 class ShowProfile extends Controller
 {
 public function __invoke($id)
 {
 return view('user.profile', ['user' => User::findOrFail($id)]);
 }
 }
Khi đó bạn đăng ký một route cho một action controllers, bạn không cần
xác định phương thức:
 Route::get('user/{id}', 'ShowProfile'); 8
 Example
Step 1 − Execute the following command to create UserController.
 php artisan make:controller UserController --plain
Step 2 − After successful execution, you will receive the following output.
Step 3 − You can see the created controller at 
app/Http/Controller/UserController.php with some basic coding already written 
for you and you can add your own coding based on your need.
 <?php
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use App\Http\Requests;
 use App\Http\Controllers\Controller;
 class UserController extends Controller {
 //
 }
 9
 HTTP Requests
− Accessing The Request
− Request Path & Method
− Retrieving Input
− Files
 • Retrieving Uploaded Files
 • Storing Uploaded Files
 10
 HTTP Requests
− Lấy đối tượng hiện tại của HTTP request
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 class UserController extends Controller
 {
 public function store(Request $request)
 {
 $name = $request->input('name');
 //
 }
 }
 11
 Dependency Injection & Route Parameters
− Khi controller cần lấy input từ tham số route thì
 • Phải liệt kê danh sách tham số route vào sau các
 dependencies.
 Route::put('user/{id}', 'UserController@update');
 12
 Dependency Injection & Route Parameters
− Truy cập vào tham số route id bằng cách định nghĩa
 phương thức trong controller
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 class UserController extends Controller
 {
 public function update(Request $request, $id)
 {
 //
 }
 }
 13
 Đường dẫn Request & Phương thức
− Nhận đường dẫn Request
 • Phương thức path trả về thông tin đường dẫn của request.
 • Vì vậy, nếu request gửi đến là 
 phương thức path sẽ trả về foo/bar:
 $uri = $request->path();
− Phương thức is: xác nhận những request gửi đến có đường dẫn
 khớp với pattern hay không. Có thể sử dụng ký tự *
 if ($request->is('admin/*')) {
 // 
 }
 14
 Nhận Request URL
− Để nhận đường dẫn đầy đủ URL từ request gửi
 • => phương thức url or fullUrl.
 // Without Query String...
 $url = $request->url();
 // With Query String...
 $url = $request->fullUrl();
 15
 Nhận phương thức Request
− Phương thức method: trả về phương thức HTTP tương ứng
 với request.
− Phương thức isMethod: xác thực phương thức HTTP khớp
 với string
 $method = $request->method();
 if ($request->isMethod('post')) {
 //
 }
 16
 Lấy tất cả dữ liệu Input
− Phương thức all(): Lấy tất cả dữ liệu input như một
 array
 $input = $request->all();
 17
 Lấy giá trị một Input
− Phương thức input
 $name = $request->input('name');
− Có thể truyền giá trị của tham số như là một đối số thứ hai
 trong phương thức input. Giá trị sẽ được trả về nếu giá trị
 input không có trong request
 $name = $request->input('name', 'Sally');
− Khi làm việc với form chứa mảng input, sử dụng dấm "chấm"
 để truy cập giá trị của mảng
 $name = $request->input('products.0.name');
 $names = $request->input('products.*.name');
 18
 Lấy Input qua thuộc tính động
− Nếu form ứng dụng có chứa trường name, có thể truy lấy giá
 trị bằng cách:
 $name = $request->name;
 19
 Lấy giá trị JSON Input
− Khi gửi JSON requests đến ứng dụng, có thể lấy dữ liệu JSON
 qua phương thức input (Content-Type header của request là
 application/json).
− Có thể dùng cú pháp "dấu chấm" để lấy giá trị mảng JSON
 $name = $request->input('user.name');
 20
 Lấy một phần dữ liệu Input
− Khi cần một tập con dữ liệu input, có thể sử dụng phương thức
 only và except.
 • Cả hai phương thức đều nhận một array hoặc một danh sách
 các đối số
 $input = $request->only(['username', 'password']);
 $input = $request->only('username', 'password');
 $input = $request->except(['credit_card']);
 $input = $request->except('credit_card');
 21
 Kiểm tra giá trị Input Value tồn tại
− Phương thức has kiểm tra giá trị input tồn tại trong request.
 Phương thức has trả về true nếu giá trị tồn tại và không phải
 chuỗi rỗng
 if ($request->has('name')) {
 //
 }
 22
 Files Uploaded
− Phương thức file
 • Trả về một class Illuminate\Http\UploadedFile, nó kế thừa
 từ SplFileInfo class
 $file = $request->file('photo');
 $file = $request->photo;
 • Phương thức hasFile: Kiểm tra một file có tồn tại trên
 request hay không bằng cách dùng
 if ($request->hasFile('photo')) {
 //
 }
 23
 Đường dẫn File & Extensions
− Phương thức path lấy đường dẫn đầy đủ và extension của file
 tạm.
− Phương thức extension: extension trên dựa nội dung của file.
 $path = $request->photo->path();
 $extension = $request->photo->extension();
 24
 Một số hàm 
File name: $request->photo->getClientOriginalName();
File Extension: $request->photo->getClientOriginalExtension();
File temp Path: $request->photo->getRealPath();
File Size: $request->photo->getSize();
File Mime Type: $request->photo->getMimeType();
 25
 Lưu Files Uploaded: hàm move()
$request->photo>move( file path, file name);
 Lưu Files Uploaded
− store chuyển file upload lên host
− Ngoài ra: tham số thứ hai => nơi lưu file.
 $path = $request->photo->store('images');
 $path = $request->photo->store('images', 's3');
− storeAs: nhận tham số như đường dẫn, tên file, và
 tên nơi lưu
 $path = $request->photo->storeAs('images', 'filename.jpg');
 $path = $request->photo->storeAs('images', 'filename.jpg', 's3');
 Request – Example 1
Step 1: php artisan make:controller UriController
Step 2: app\Http\Controllers\UriController.php
 namespace App\Http\Controllers; Step 3 − Add the following line in 
 use Illuminate\Http\Request; the routes\web.php
 use App\Http\Requests;
 use App\Http\Controllers\Controller; Route::get('/foo/bar','UriCon
 class UriController extends Controller { troller@index');
 public function index(Request $request){
 $path = $request->path();
 echo 'Path Method: '.$path;
 echo ''; 
 $pattern = $request->is('foo/*');
 echo 'is Method: '.$pattern; Step 4: 
 echo '';
 $url = $request->url();
 echo 'URL method: '.$url;
 }
 }
 28
 Request – Example 2
 Step 1: Create a Registration form, where user can register himself and store 
 the form at resources/views/register.php
Form Example
 ">
 Name 
 Username 
 Password 
 29
 Request – Example 2
Step 2 − Execute the below command to create a UserRegistration controller.
 php artisan make:controller UserRegistration
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use App\Http\Requests;
 use App\Http\Controllers\Controller;
 class UserRegistration extends Controller {
 public function postRegister(Request $request){
 $name = $request->input('name');
 echo 'Name: '.$name;
 echo '';
 $username = $request->username;
 echo 'Username: '.$username;
 echo '';
 $password = $request->password;
 echo 'Password: '.$password;
 } 30
 }
 Request – Example 2
Step 3 − Add the following line in routes/web.php file.
 Route::get('/register',function(){
 return view('register');
 });
 Route::post('/user/register',array('uses'=>'UserRegistration@postRegister'
 ));
Step 4− Visit the following URL and you will see the registration form as 
shown in the below figure. Type the registration details and click Register and 
you will see on the second page that we have retrieved and displayed the user 
registration details: 
Step 5 − The output will look something like as shown in below the following 
images.
 31
 HTTP Responses
− Creating Responses
− Redirects
 • Redirecting To Named Routes
 • Redirecting To Controller Actions
− Other Response Types
 • View Responses
 • JSON Responses
 • File Downloads
 • File Responses
 32
 HTTP Responses
− Các route và controller nên trả về một response để gửi cho
 người dùng trình duyệt.
 Route::get('/', function () {
 return 'Hello World';
 });
− Trả về mảng => framework sẽ tự động chuyển mảng thành
 JSON response
 Route::get('/', function () {
 return [1, 2, 3];
 });
 33
 JSON Response
− json method.
− Automatically set the Content-Type header to application/json.
− The json method will automatically convert the array into
 appropriate json response.
 Route::get('json',function(){
 return response()->json(['name' => 'Laravel', 'version' => '5.3']);
 });
 34
 Response Objects
− Trả về đầy đủ Illuminate\Http\Response instances hoặc views.
 Route::get('home', function () {
 return response('Hello World', 200)
 ->header('Content-Type', 'text/plain');
 });
 35
 Chuyển trang
− Chuyển responses là thể hiện của class
 Illuminate\Http\RedirectResponse
 Route::get('dashboard', function () {
 return redirect('home/dashboard');
 });
− Chuyển trang của người dùng đến trang trước đó
 Route::post('user/profile', function () {
 // Validate the request...
 return back()->withInput();
 });
 36
 Chuyển trang về tên routes
 return redirect()->route('login');
− Nếu route của bạn có tham số
 return redirect()->route('profile', ['id' => 1]);
 37
 Chuyển trang đến Controller Actions
 return redirect()->action('HomeController@index');
− Nếu controller route có tham số => truyền qua như là tham số
 thứ hai của phương thức action
 return redirect()->action(
 'UserController@profile', ['id' => 1]
 );
 38
 File Downloads
− Phương thức download: tạo response bắt trình duyệt của
 người dùng tải file tại đường dẫn.
 • Tham số thứ hai: tên file.
 • Tham số thứ ba: mảng HTTP headers
 return response()->download($pathToFile);
 return response()->download($pathToFile, $name, $headers);
 39
 File Responses
− Phương thức file: hiển thị một file (như là ảnh hoặc PDF) trực
 tiếp trong trình duyệt của người dùng thay vì phải tải.
 return response()->file($pathToFile);
 return response()->file($pathToFile, $headers);
 40
 HTTP Session
− Introduction
− Using The Session
 • Retrieving Data
 • Storing Data
 41
 HTTP Session
− Sessions cung cấp một cách để lưu thông tin từ các yêu cầu
 của người dùng.
− Nhận dữ liệu
 • Cách truy cập session qua thể hiện Request
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use App\Http\Controllers\Controller;
 class UserController extends Controller
 {
 public function show(Request $request, $id)
 {
 $value = $request->session()->get('key');
 //
 }
 }
 42
 HTTP Session
− Sử dụng hàm global session của PHP và lưu dữ liệu trong
 session
 Route::get('home', function () {
 // Retrieve a piece of data from the session...
 $value = session('key');
 // Specifying a default value...
 $value = session('key', 'default');
 // Store a piece of data in the session...
 session(['key' => 'value']);
 });
 43
 HTTP Session
− Nhận tất cả dữ liệu Session
 $data = $request->session()->all();
− Kiểm tra sự tồn tại của Session: has
 if ($request->session()->has('users')) {
 //
 }
− Phương thức exists: trả về true nếu giá trị tồn tại
 if ($request->session()->exists('users')) {
 //
 }
 44
 Storing Session Data
− Phương thức put hoặc session
 // Via a request instance...
 $request->session()->put('key', 'value');
 // Via the global helper...
 session(['key' => 'value']);
− Phương thức pull sẽ nhận và xóa một item từ session
 $value = $request->session()->pull('key', 'default');
 45
 Deleting Session Data
− forget(): delete an item from the session.
− This method will take “key” as the argument.
 $request->session()->forget('key');
 46
 Example
− Step 1: php artisan make:controller SessionController
− Step 2: namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use App\Http\Requests;
 use App\Http\Controllers\Controller;
 class SessionController extends Controller {
 public function accessSessionData(Request $request) {
 if ($request->session ()->has ( 'my_name' ))
 echo $request->session ()->get ( 'my_name' );
 else
 echo 'No data in the session';
 }
 public function storeSessionData(Request $request) {
 $request->session ()->put ( 'my_name', 'Laravel 5.x' );
 echo "Data has been added to session";
 }
 public function deleteSessionData(Request $request) {
 $request->session ()->forget ( 'my_name' );
 echo "Data has been removed from session.";
 }
 47
 }
 Example
− Step 3: Route
 Route::get('session/get','SessionController@accessSessionData');
 Route::get('session/set','SessionController@storeSessionData');
 Route::get('session/remove','SessionController@deleteSessionData');
− Step 4: 
 48
 Example
− Step 5: 
− Step 6: 
 49
 Bảo mật CSRF
− Laravel bảo vệ ứng dụng từ tấn công giả mạo cross-site
 request forgery (CSRF).
 • Cross-site request forgery là một loại mã độc: các lệnh trái phép
 được thực hiện thay cho một người dùng đã xác thực.
− Laravel tự động tạo ra một CSRF "token" cho mỗi người dùng
 hoạt động quản lý bởi ứng dụng.
 • Mã này dùng để xác minh rằng người dùng là một trong những
 người dùng thực sự gửi yêu cầu đến ứng dụng.
− Khi tạo một HTML form, phải thêm trường CSRF token vào
 trong form để bảo mật CSRF middleware có thể xác nhận
 request.
 50
 Bảo mật CSRF
− Sử dụng csrf_field để sinh ra trường CSRF token
 {{ csrf_field() }}
 ...
 ">
 51
 File Uploading
− Chúng ta cần tạo:
 • file view => chọn file để tải lên 
 • controller nơi mà các file đã được tải lên sẽ được xử lý.
− Trong một file view, chúng ta cần phải tạo một file đầu vào 
 bằng cách:
 Form::file('file_name');
− Trong Form::open(), thêm vào ‘files’=> ‘true’ như bên dưới
 => tạo điều kiện cho form được upload in multiple parts.
 Form::open(array('url' => '/uploadfile','files'=>'true'));
 52
 File Uploading - Example
− Step 1 − Create a view file resources/views/uploadfile.php
 <?php
 echo Form::open(array('url' => '/uploadfile','files'=>'true'));
 echo 'Select the file to upload.';
 echo Form::file('image');
 echo Form::submit('Upload File');
 echo Form::close();
 ?>
 53
 File Uploading - Example
− Step 2 − Create a controller called UploadFileController by 
 executing the following command.
 php artisan make:controller UploadFileController
− Step 3 − Code in app/Http/Controllers/UploadFileController.php
 54
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UploadFileController extends Controller {
 public function index(){
 return view('uploadfile');
 }
 public function showUploadFile(Request $request){
 $file = $request->file('image');
 echo 'File Name: '.$file->getClientOriginalName();
 echo '';
 echo 'File Extension: '.$file->getClientOriginalExtension();
 echo '';
 echo 'File Real Path: '.$file->getRealPath();
 echo '';
 echo 'File Size: '.$file->getSize();
 echo '';
 //Display File Mime Type
 echo 'File Mime Type: '.$file->getMimeType();
 //Move Uploaded File: public/uploads/
 $destinationPath = 'uploads';
 $file->move($destinationPath,$file->getClientOriginalName());
 } 55
}
 File Uploading - Example
− Step 5 − Add the following lines in routes\web.php
 Route::get('/uploadfile','UploadFileController@index');
 Route::post('/uploadfile','UploadFileController@showUploadFile');
− Step 6 − Visit the following URL: 
 56

File đính kèm:

  • pdfbai_giang_phat_trien_phan_mem_nguon_mo_bai_8_controllers_req.pdf