Bài giảng Phát triển phần mềm nguồn mở - Bài 9: Controllers, Request, Response, Session - Nguyễn Hữu Thể

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 $name = $request->input('name'); $name = $request->input('name', 'Sally'); $name = $request->input('products.0.name'); $names = $request->input('products.*.name');

pdf31 trang | Chia sẻ: thanhle95 | Lượt xem: 420 | Lượt tải: 1download
Bạn đang xem trước 20 trang tài liệu Bài giảng Phát triển phần mềm nguồn mở - Bài 9: Controllers, Request, Response, Session - Nguyễn Hữu Thể, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
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 app/Http/routes.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' ));
Tài liệu liên quan