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

− Introduction

− Basic Controllers

• Defining Controllers

• Controllers & Namespaces

• Single Action Controllers

pdf 56 trang yennguyen 3200
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ể
CONTROLLERS, REQUEST, RESPONSE, SESSION
Nguyễn Hữu Thể
PHÁT TRIỂN PHẦN MỀM NGUỒN MỞ
Controllers
− Introduction
− Basic Controllers
• Defining Controllers
• Controllers & Namespaces
• Single Action Controllers
2
">
Name 
<?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;
}
} 
Route::get ( '/register', function () {
return view ( ‘nhap' );
} );
Route::post('/user/register’,’MyController@postRegister');
1 View: nhap.blade.php
2. Controller: MyController.php
3. Route:
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
6
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)]);
}
}
Controllers
7
▪ Định nghĩa một route cho action của controller
▪ Khi request với route URI, phương thức show của class 
UserController sẽ được thực thi. 
Route::get('user/{id}', 'UserController@show');
Action Controllers
__invoke(): Định nghĩa một controller xử lý duy nhất một action
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:
8
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)]);
}
}
Route::get('user/{id}', 'ShowProfile');
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
11
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function store(Request $request)
{
$name = $request->input('name');
//
}
}
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.
12
Route::put('user/{id}', 'UserController@update');
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
13
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function update(Request $request, $id)
{
//
}
}
Đườ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:
− 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ự *
14
$uri = $request->path();
if ($request->is('admin/*')) {
// 
}
Nhận Request URL
− Để nhận đường dẫn đầy đủ URL từ request gửi
• => phương thức url or fullUrl.
15
// Without Query String...
$url = $request->url();
// With Query String...
$url = $request->fullUrl();
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
16
$method = $request->method();
if ($request->isMethod('post')) {
//
}
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
17
$input = $request->all();
Lấy giá trị một Input
− Phương thức input
− 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
− 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
18
$name = $request->input('name');
$name = $request->input('name', 'Sally');
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');
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:
19
$name = $request->name;
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
20
$name = $request->input('user.name');
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ố
21
$input = $request->only(['username', 'password']);
$input = $request->only('username', 'password');
$input = $request->except(['credit_card']);
$input = $request->except('credit_card');
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
22
if ($request->has('name')) {
//
}
Files Uploaded
− Phương thức file
• Trả về một class Illuminate\Http\UploadedFile, nó kế thừa
từ SplFileInfo class
• 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
23
$file = $request->file('photo');
$file = $request->photo;
if ($request->hasFile('photo')) {
//
}
Đườ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.
24
$path = $request->photo->path();
$extension = $request->photo->extension();
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.
− 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');
$path = $request->photo->store('images');
$path = $request->photo->store('images', 's3');
Request – Example 1
Step 1: php artisan make:controller UriController
Step 2: app\Http\Controllers\UriController.php
28
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UriController extends Controller { 
public function index(Request $request){
$path = $request->path();
echo 'Path Method: '.$path;
echo ''; 
$pattern = $request->is('foo/*');
echo 'is Method: '.$pattern;
echo '';
$url = $request->url();
echo 'URL method: '.$url;
}
}
Step 3 − Add the following line in 
the routes\web.php
Route::get('/foo/bar','UriCon
troller@index');
Step 4: 
Request – Example 2
Step 1: Create a Registration form, where user can register himself and store 
the form at resources/views/register.php
29
Form Example
">
Name 
Username 
Password 
Request – Example 2
Step 2 − Execute the below command to create a UserRegistration controller.
php artisan make:controller UserRegistration
30
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;
}
}
Request – Example 2
Step 3 − Add the following line in routes/web.php file.
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
Route::get('/register',function(){
return view('register');
});
Route::post('/user/register',array('uses'=>'UserRegistration@postRegister'
));
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.
− Trả về mảng => framework sẽ tự động chuyển mảng thành
JSON response
33
Route::get('/', function () {
return 'Hello World';
});
Route::get('/', function () {
return [1, 2, 3];
});
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.
34
Route::get('json',function(){
return response()->json(['name' => 'Laravel', 'version' => '5.3']);
});
Response Objects
− Trả về đầy đủ Illuminate\Http\Response instances hoặc views.
35
Route::get('home', function () {
return response('Hello World', 200)
->header('Content-Type', 'text/plain');
});
Chuyển trang
− Chuyển responses là thể hiện của class
Illuminate\Http\RedirectResponse
− Chuyển trang của người dùng đến trang trước đó
36
Route::get('dashboard', function () {
return redirect('home/dashboard');
});
Route::post('user/profile', function () {
// Validate the request...
return back()->withInput();
});
Chuyển trang về tên routes
− Nếu route của bạn có tham số
37
return redirect()->route('login');
return redirect()->route('profile', ['id' => 1]);
Chuyển trang đến Controller Actions
− Nếu controller route có tham số => truyền qua như là tham số
thứ hai của phương thức action
38
return redirect()->action('HomeController@index');
return redirect()->action(
'UserController@profile', ['id' => 1]
);
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
39
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
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.
40
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
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
42
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');
//
}
}
HTTP Session
− Sử dụng hàm global session của PHP và lưu dữ liệu trong
session
43
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']);
});
HTTP Session
− Nhận tất cả dữ liệu Session
− Kiểm tra sự tồn tại của Session: has
− Phương thức exists: trả về true nếu giá trị tồn tại
44
$data = $request->session()->all();
if ($request->session()->has('users')) {
//
}
if ($request->session()->exists('users')) {
//
}
Storing Session Data
− Phương thức put hoặc session
− Phương thức pull sẽ nhận và xóa một item từ session
45
// Via a request instance...
$request->session()->put('key', 'value');
// Via the global helper...
session(['key' => 'value']);
$value = $request->session()->pull('key', 'default');
Deleting Session Data
− forget(): delete an item from the session.
− This method will take “key” as the argument.
46
$request->session()->forget('key');
Example
− Step 1: php artisan make:controller SessionController
− Step 2:
47
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.";
}
}
Example
− Step 3: Route
− Step 4: 
48
Route::get('session/get','SessionController@accessSessionData');
Route::get('session/set','SessionController@storeSessionData');
Route::get('session/remove','SessionController@deleteSessionData');
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
51
{{ csrf_field() }}
...
">
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:
− 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.
52
Form::file('file_name');
Form::open(array('url' => '/uploadfile','files'=>'true'));
File Uploading - Example
− Step 1 − Create a view file resources/views/uploadfile.php
53
<?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();
?>
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
55
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());
}
}
File Uploading - Example
− Step 5 − Add the following lines in routes\web.php
− Step 6 − Visit the following URL: 
56
Route::get('/uploadfile','UploadFileController@index');
Route::post('/uploadfile','UploadFileController@showUploadFile');

File đính kèm:

  • pdfbai_giang_phat_trien_phan_mem_nguon_mo_chuong_8_controllers.pdf