SlideShare a Scribd company logo
Wykorzystanie Form Request
przy implementacji API w
Laravelu
Marek Tenus
Full-stack Senior Developer
marek@highsolutions.pl
#1 - Architektura projektu
● NativeScript
● Angular
● TypeScript
● CSS (NativeScript)
● HTML (NativeScript)
#1 - Architektura projektu
● PHP 7.1
● MySQL 5.7
● Laravel 5.5
#1 - Architektura projektu
● PHP 7.1
● MySQL 5.7
● Laravel 5.5
● CSS3
● HTML5
● JavaScript
#2 - Konstrukcja API
DB
#2 - Konstrukcja API
DB
#2 - Konstrukcja API
DB
Client
#2 - Konstrukcja API
DB
Client
Server
#2 - Konstrukcja API
DB
#2 - Konstrukcja API
DB
#2 - Konstrukcja API
#2 - Konstrukcja API
Client
● Send request
● Get response
#2 - Konstrukcja API
Server
● Get request
● Handle request
● Return response
#2 - Konstrukcja API
Auth/Token
request / HTTPS (POST/GET/DELETE/PUT)
#2 - Konstrukcja API
request / HTTPS (POST/GET/DELETE/PUT)
/api/article/1
REST Interface
Auth/Token
#2 - Konstrukcja API
reponse / JSON
#3 - Klasyczna obsługa żądań
Routes
#3 - Klasyczna obsługa żądań
Routes
/api/article GET index
/api/article POST store
#3 - Klasyczna obsługa żądań
Routes Middleware
/api/article GET index
/api/article POST store
#3 - Klasyczna obsługa żądań
Routes Middleware
/api/article GET index
/api/article POST store
allow or deny
#3 - Klasyczna obsługa żądań
Routes Middleware Controller
/api/article GET index
/api/article POST store
allow or deny
#3 - Klasyczna obsługa żądań
Routes Middleware Controller
/api/article GET index
/api/article POST store
allow or deny
get request
handle request
do some stuff
return response
#3 - Klasyczna obsługa żądań
Routes Middleware Controller
/api/article GET index
/api/article POST store
allow or deny
get request
handle request
do some stuff
return response
#3 - Klasyczna obsługa żądań
namespace AppHttpControllersEventController;
use AppHttpControllersController;
use IlluminateHttpRequest;
class EventController extends Controller
{
}
#3 - Klasyczna obsługa żądań
namespace AppHttpControllersEventController;
use AppHttpControllersController;
use IlluminateHttpRequest;
class EventController extends Controller
{
}
#3 - Klasyczna obsługa żądań
public function __construct() {}
public function index() {} //GET
public function create() {} //GET
public function store() {} //POST
public function edit() {} //GET
public function update() {} //PUT/PATCH
public function destroy() {} //DELETE
#3 - Klasyczna obsługa żądań
public function store(Request $request) {
}
#3 - Klasyczna obsługa żądań
public function store(Request $request) {
}
Dependency Injection
#3 - Klasyczna obsługa żądań
public function store() {
$request = request();
}
#3 - Klasyczna obsługa żądań
public function store() {
$request = request();
}
Current instance of Request
#3 - Klasyczna obsługa żądań
public function store(Request $request) {
//authorize the request access(?)
//check if the request has valid data
//store the event member
//give some response
}
#3 - Klasyczna obsługa żądań
//authorize the request access(?)
abort_if(!$request->ajax(), 403);
//check if request has valid data
$request->validate([
'first_name' => 'required|max:191',
'last_name' => 'required|max:191',
'department_id' => 'required|exists:departments,id',
'note' => 'max:512',
]);
//store the event member
EventMember::create($request->all());
//give some response
return [
‘success’ => true,
];
#4 - Form Request
● Klasa dziedzicząca z klasy Request
● Posiada wbudowaną logikę walidacji
● Autoryzacja dostępu do wykonania żądania
● Czy pozwala na więcej?!
#4 - Form Request
Routes Middleware Controller
/api/article GET index
/api/article POST store
allow or deny
get request
handle request
do some stuff
return response
#4 - Form Request
Routes Middleware Controller
/api/article GET index
/api/article POST store
allow or deny
get request
do some stuff
return response
Form
Request
handle request
- validation
- authorization
#4 - Form Request
Routes Middleware Controller
/api/article GET index
/api/article POST store
allow or deny
get request
do some stuff
return response
Form
Request
handle request
- validation
- authorization
#4 - Form Request
php artisan make:request StoreEventMemberRequest
#4 - Form Request
namespace AppHttpRequests;
use IlluminateFoundationHttpFormRequest;
class StoreEventMemberRequest extends FormRequest
{
public function authorize()
{
return false;
}
public function rules()
{
return [
];
}
}
#4 - Form Request
class StoreEventMemberRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
];
}
}
#4 - Form Request
class StoreEventMemberRequest extends FormRequest
{
public function authorize()
{
return true;
}
}
#4 - Form Request
class StoreEventMemberRequest extends FormRequest
{
public function authorize()
{
return $this->ajax();
}
}
true => access
false => 403
#4 - Form Request
class StoreEventMemberRequest extends FormRequest
{
public function authorize()
{
return $this->ajax();
}
} protected function failedAuthorization()
{
throw new HttpResponseException($this->forbiddenResponse());
}
true => access
false => 403
#4 - Form Request
class StoreEventMemberRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'first_name' => 'required|max:191',
'last_name' => 'required|max:191',
'department_id' => 'required|exists:departments,id',
'note' => 'max:512',
];
}
}
#4 - Form Request
public function messages()
{
return [
‘first_name.required’ => ‘Your first name is required’,
‘last_name.required’ => ‘Your last name is required’,
];
}
#4 - Form Request
public function attributes()
{
return [
‘first_name’ => ‘Your first name’,
‘last_name’ => ‘Your last name’,
];
}
#4 - Form Request
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
}
#4 - Form Request
use AppHttpControllersController;
use IlluminateHttpRequest;
use AppHttpRequestsStoreEventMemberRequest;
class EventController extends Controller
{
}
#4 - Form Request
public function store(StoreEventMemberRequest $request)
{
//authorize the request access(?)
//check if request has valid data
//store the event member
//give some response
}
#4 - Form Request
//authorize the request access(?)
abort_if(!$request->ajax(), 403);
//check if request has valid data
$request->validate([
'first_name' => 'required|max:191',
'last_name' => 'required|max:191',
'department_id' => 'required|exists:departments,id',
'note' => 'max:512',
]);
//store the event member
EventMember::create($request->all());
//give some response
return [
‘success’ => true,
];
#4 - Form Request
//authorize the request access(?)
abort_if(!$request->ajax(), 403);
//check if request has valid data
$request->validate([
'first_name' => 'required|max:191',
'last_name' => 'required|max:191',
'department_id' => 'required|exists:departments,id',
'note' => 'max:512',
]);
//store the event member
EventMember::create($request->all());
//give some response
return [
‘success’ => true,
];
#4 - Form Request
public function store(StoreEventMemberRequest $request) {
EventMember::create($request->all());
return [
‘success’ => true,
];
}
#4 - Form Request
#4 - Form Request
Czy pozwala na
więcej?!
#4 - Form Request
● Oczyszczanie danych formularza (sanitizing)
● Manipulacja danymi formularza (handling)
● Logowanie zdarzeń (logging)
#5 - Zastosowanie Form Request w projekcie
● Oczyszczanie danych formularza (sanitizing)
● Manipulacja danymi formularza (handling)
● Logowanie zdarzeń (logging)
#5 - Zastosowanie Form Request w projekcie
public function all()
{
}
#5 - Zastosowanie Form Request w projekcie
public function all()
{
$attributes = parent::all();
return collect($attributes)
->map(function($field) {
return $field ?? filter_var($field,
FILTER_SANITIZE_STRING);
})
->all();
}
#5 - Zastosowanie Form Request w projekcie
public function all()
{
$attributes = parent::all();
return collect($attributes)
->map(function($field) {
return $field ?? filter_var($field,
FILTER_SANITIZE_STRING);
})
->all();
}
$_POST[‘data’] = [...];
422 (Unprocessable Entity)
#5 - Zastosowanie Form Request w projekcie
public function all()
{
$attributes = parent::all();
return collect($attributes)
->map(function($field) {
return $field ?? filter_var($field,
FILTER_SANITIZE_STRING);
})
->all();
}
$_POST[‘data’] = [...];
422 (Unprocessable Entity)
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson()) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
#5 - Zastosowanie Form Request w projekcie
public function all()
{
$attributes = parent::all();
return $this->sanitizeAttributes($attributes);
}
$_POST[‘data’] = [...];
protected function sanitizeAttributes($attributes) {
return collect($attributes)
->map(function($field) {
return $field ?? filter_var($field,
FILTER_SANITIZE_STRING);
})
->all();
}
#5 - Zastosowanie Form Request w projekcie
public function all()
{
$attributes = $this->input('data');
$attributes['token'] = $this->input('token');
return $this->sanitizeAttributes($attributes);
}
#5 - Zastosowanie Form Request w projekcie
public function all()
{
return $this->sanitizeAttributes($this->handleAttributes());
}
protected function handleAttributes() {
$attributes = $this->input('data');
$attributes['token'] = $this-
>input('token');
return $attributes;
}
#5 - Zastosowanie Form Request w projekcie
public function all()
{
return $this->sanitizeAttributes($this->handleAttributes());
}
protected function handleAttributes() {
if(!$this->has(‘data’)) {
return parent::all();
}
$attributes = $this->input('data');
$attributes['token'] = $this->input('token');
return $attributes;
}
#6 - Podsumowanie
Zalety
● Clean code
● Dependency Injection
● Security
● Reusability
#6 - Podsumowanie
Wady
● Łamie SRP (Single Responsibility Principle)
● Przesadne używanie Form Request
Marek Tenus
marek@highsolutions.pl

More Related Content

What's hot

Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
som_nangia
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
Shinya Ohyanagi
 
Webrtc mojo
Webrtc mojoWebrtc mojo
Webrtc mojo
bpmedley
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
Jace Ju
 
Express JS
Express JSExpress JS
Express JS
Alok Guha
 
RESTful web services
RESTful web servicesRESTful web services
RESTful web services
Tudor Constantin
 
Web service with Laravel
Web service with LaravelWeb service with Laravel
Web service with Laravel
Abuzer Firdousi
 
Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101
hendrikvb
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
Tatsuhiko Miyagawa
 
Zend framework
Zend frameworkZend framework
Zend framework
Prem Shankar
 
Building com Phing - 7Masters PHP
Building com Phing - 7Masters PHPBuilding com Phing - 7Masters PHP
Building com Phing - 7Masters PHP
iMasters
 
Phinx talk
Phinx talkPhinx talk
Phinx talk
Michael Peacock
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
Samantha Geitz
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & Application
Jace Ju
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
Phil Sturgeon
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
shaokun
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
shaokun
 
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
Shengyou Fan
 
Tatsumaki
TatsumakiTatsumaki
Alfresco study presentation 38th customize How-To WebDAV
Alfresco study presentation 38th customize How-To WebDAVAlfresco study presentation 38th customize How-To WebDAV
Alfresco study presentation 38th customize How-To WebDAV
Takeshi Totani
 

What's hot (20)

Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Webrtc mojo
Webrtc mojoWebrtc mojo
Webrtc mojo
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
 
Express JS
Express JSExpress JS
Express JS
 
RESTful web services
RESTful web servicesRESTful web services
RESTful web services
 
Web service with Laravel
Web service with LaravelWeb service with Laravel
Web service with Laravel
 
Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 
Zend framework
Zend frameworkZend framework
Zend framework
 
Building com Phing - 7Masters PHP
Building com Phing - 7Masters PHPBuilding com Phing - 7Masters PHP
Building com Phing - 7Masters PHP
 
Phinx talk
Phinx talkPhinx talk
Phinx talk
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & Application
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
 
Tatsumaki
TatsumakiTatsumaki
Tatsumaki
 
Alfresco study presentation 38th customize How-To WebDAV
Alfresco study presentation 38th customize How-To WebDAVAlfresco study presentation 38th customize How-To WebDAV
Alfresco study presentation 38th customize How-To WebDAV
 

Similar to Wykorzystanie form request przy implementacji API w Laravelu

関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Chekout demistified
Chekout demistifiedChekout demistified
Chekout demistified
Damijan Ćavar
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 
Application Layer in PHP
Application Layer in PHPApplication Layer in PHP
Application Layer in PHP
Per Bernhardt
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
Bastian Hofmann
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Bastian Hofmann
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
Jeroen van Dijk
 
22.sessions in laravel
22.sessions in laravel22.sessions in laravel
22.sessions in laravel
Razvan Raducanu, PhD
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
Jeroen van Dijk
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
Darren Craig
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
Michelangelo van Dam
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
Michelangelo van Dam
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
Ben Scheirman
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
joaopmaia
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
Michelangelo van Dam
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
Kirk Bushell
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
Michelangelo van Dam
 
PSR-7, middlewares e o futuro dos frameworks
PSR-7, middlewares e o futuro dos frameworksPSR-7, middlewares e o futuro dos frameworks
PSR-7, middlewares e o futuro dos frameworks
Elton Minetto
 

Similar to Wykorzystanie form request przy implementacji API w Laravelu (20)

関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Chekout demistified
Chekout demistifiedChekout demistified
Chekout demistified
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
Application Layer in PHP
Application Layer in PHPApplication Layer in PHP
Application Layer in PHP
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
22.sessions in laravel
22.sessions in laravel22.sessions in laravel
22.sessions in laravel
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
PSR-7, middlewares e o futuro dos frameworks
PSR-7, middlewares e o futuro dos frameworksPSR-7, middlewares e o futuro dos frameworks
PSR-7, middlewares e o futuro dos frameworks
 

More from Laravel Poland MeetUp

WebRTC+Websockety - Jak stworzyłem aplikację do kamerek internetowych w Larav...
WebRTC+Websockety - Jak stworzyłem aplikację do kamerek internetowych w Larav...WebRTC+Websockety - Jak stworzyłem aplikację do kamerek internetowych w Larav...
WebRTC+Websockety - Jak stworzyłem aplikację do kamerek internetowych w Larav...
Laravel Poland MeetUp
 
xD bug - Jak debugować PHP-owe aplikacje (Xdebug)
xD bug - Jak debugować PHP-owe aplikacje (Xdebug) xD bug - Jak debugować PHP-owe aplikacje (Xdebug)
xD bug - Jak debugować PHP-owe aplikacje (Xdebug)
Laravel Poland MeetUp
 
Kilka slajdów o castowaniu atrybutów w Eloquent
Kilka slajdów o castowaniu atrybutów w EloquentKilka slajdów o castowaniu atrybutów w Eloquent
Kilka slajdów o castowaniu atrybutów w Eloquent
Laravel Poland MeetUp
 
Licencje otwartego oprogramowania
Licencje otwartego oprogramowaniaLicencje otwartego oprogramowania
Licencje otwartego oprogramowania
Laravel Poland MeetUp
 
Jak przyspieszyłem aplikację produkcyjną o ponad 40%
Jak przyspieszyłem aplikację produkcyjną o ponad 40%Jak przyspieszyłem aplikację produkcyjną o ponad 40%
Jak przyspieszyłem aplikację produkcyjną o ponad 40%
Laravel Poland MeetUp
 
Jak przemycić Shape Up do Scruma?
Jak przemycić Shape Up do Scruma?Jak przemycić Shape Up do Scruma?
Jak przemycić Shape Up do Scruma?
Laravel Poland MeetUp
 
Cykl życia zapytania HTTP (pod maską)
Cykl życia zapytania HTTP (pod maską)Cykl życia zapytania HTTP (pod maską)
Cykl życia zapytania HTTP (pod maską)
Laravel Poland MeetUp
 
Enumy w Laravelu - dlaczego warto stosować?
Enumy w Laravelu - dlaczego warto stosować?Enumy w Laravelu - dlaczego warto stosować?
Enumy w Laravelu - dlaczego warto stosować?
Laravel Poland MeetUp
 
Laravelowe paczki do uwierzytelniania
Laravelowe paczki do uwierzytelnianiaLaravelowe paczki do uwierzytelniania
Laravelowe paczki do uwierzytelniania
Laravel Poland MeetUp
 
Przegląd najciekawszych wtyczek do Laravela
Przegląd najciekawszych wtyczek do LaravelaPrzegląd najciekawszych wtyczek do Laravela
Przegląd najciekawszych wtyczek do Laravela
Laravel Poland MeetUp
 
Walidacja w Laravelu
Walidacja w LaraveluWalidacja w Laravelu
Walidacja w Laravelu
Laravel Poland MeetUp
 
(prawie) Wszystko o Tinkerze
(prawie) Wszystko o Tinkerze(prawie) Wszystko o Tinkerze
(prawie) Wszystko o Tinkerze
Laravel Poland MeetUp
 
Laravel Dusk - prosty przepis na testy E2E
Laravel Dusk - prosty przepis na testy E2ELaravel Dusk - prosty przepis na testy E2E
Laravel Dusk - prosty przepis na testy E2E
Laravel Poland MeetUp
 
Laravel Octane - czy na pewno taki szybki?
Laravel Octane - czy na pewno taki szybki?Laravel Octane - czy na pewno taki szybki?
Laravel Octane - czy na pewno taki szybki?
Laravel Poland MeetUp
 
Laravel Jobs i PHP8
Laravel Jobs i PHP8Laravel Jobs i PHP8
Laravel Jobs i PHP8
Laravel Poland MeetUp
 
Wszystko o Laravel Livewire
Wszystko o Laravel Livewire Wszystko o Laravel Livewire
Wszystko o Laravel Livewire
Laravel Poland MeetUp
 
Laravel/PHP - zderzenie z PDFami
Laravel/PHP - zderzenie z PDFamiLaravel/PHP - zderzenie z PDFami
Laravel/PHP - zderzenie z PDFami
Laravel Poland MeetUp
 
Action-based Laravel
Action-based LaravelAction-based Laravel
Action-based Laravel
Laravel Poland MeetUp
 
Automatyzacja utrzymania jakości w środowisku PHP
Automatyzacja utrzymania jakości w środowisku PHPAutomatyzacja utrzymania jakości w środowisku PHP
Automatyzacja utrzymania jakości w środowisku PHP
Laravel Poland MeetUp
 
Wstęp do Gitlab CI/CD w aplikacjach napisanych w Laravel
Wstęp do Gitlab CI/CD w aplikacjach napisanych w LaravelWstęp do Gitlab CI/CD w aplikacjach napisanych w Laravel
Wstęp do Gitlab CI/CD w aplikacjach napisanych w Laravel
Laravel Poland MeetUp
 

More from Laravel Poland MeetUp (20)

WebRTC+Websockety - Jak stworzyłem aplikację do kamerek internetowych w Larav...
WebRTC+Websockety - Jak stworzyłem aplikację do kamerek internetowych w Larav...WebRTC+Websockety - Jak stworzyłem aplikację do kamerek internetowych w Larav...
WebRTC+Websockety - Jak stworzyłem aplikację do kamerek internetowych w Larav...
 
xD bug - Jak debugować PHP-owe aplikacje (Xdebug)
xD bug - Jak debugować PHP-owe aplikacje (Xdebug) xD bug - Jak debugować PHP-owe aplikacje (Xdebug)
xD bug - Jak debugować PHP-owe aplikacje (Xdebug)
 
Kilka slajdów o castowaniu atrybutów w Eloquent
Kilka slajdów o castowaniu atrybutów w EloquentKilka slajdów o castowaniu atrybutów w Eloquent
Kilka slajdów o castowaniu atrybutów w Eloquent
 
Licencje otwartego oprogramowania
Licencje otwartego oprogramowaniaLicencje otwartego oprogramowania
Licencje otwartego oprogramowania
 
Jak przyspieszyłem aplikację produkcyjną o ponad 40%
Jak przyspieszyłem aplikację produkcyjną o ponad 40%Jak przyspieszyłem aplikację produkcyjną o ponad 40%
Jak przyspieszyłem aplikację produkcyjną o ponad 40%
 
Jak przemycić Shape Up do Scruma?
Jak przemycić Shape Up do Scruma?Jak przemycić Shape Up do Scruma?
Jak przemycić Shape Up do Scruma?
 
Cykl życia zapytania HTTP (pod maską)
Cykl życia zapytania HTTP (pod maską)Cykl życia zapytania HTTP (pod maską)
Cykl życia zapytania HTTP (pod maską)
 
Enumy w Laravelu - dlaczego warto stosować?
Enumy w Laravelu - dlaczego warto stosować?Enumy w Laravelu - dlaczego warto stosować?
Enumy w Laravelu - dlaczego warto stosować?
 
Laravelowe paczki do uwierzytelniania
Laravelowe paczki do uwierzytelnianiaLaravelowe paczki do uwierzytelniania
Laravelowe paczki do uwierzytelniania
 
Przegląd najciekawszych wtyczek do Laravela
Przegląd najciekawszych wtyczek do LaravelaPrzegląd najciekawszych wtyczek do Laravela
Przegląd najciekawszych wtyczek do Laravela
 
Walidacja w Laravelu
Walidacja w LaraveluWalidacja w Laravelu
Walidacja w Laravelu
 
(prawie) Wszystko o Tinkerze
(prawie) Wszystko o Tinkerze(prawie) Wszystko o Tinkerze
(prawie) Wszystko o Tinkerze
 
Laravel Dusk - prosty przepis na testy E2E
Laravel Dusk - prosty przepis na testy E2ELaravel Dusk - prosty przepis na testy E2E
Laravel Dusk - prosty przepis na testy E2E
 
Laravel Octane - czy na pewno taki szybki?
Laravel Octane - czy na pewno taki szybki?Laravel Octane - czy na pewno taki szybki?
Laravel Octane - czy na pewno taki szybki?
 
Laravel Jobs i PHP8
Laravel Jobs i PHP8Laravel Jobs i PHP8
Laravel Jobs i PHP8
 
Wszystko o Laravel Livewire
Wszystko o Laravel Livewire Wszystko o Laravel Livewire
Wszystko o Laravel Livewire
 
Laravel/PHP - zderzenie z PDFami
Laravel/PHP - zderzenie z PDFamiLaravel/PHP - zderzenie z PDFami
Laravel/PHP - zderzenie z PDFami
 
Action-based Laravel
Action-based LaravelAction-based Laravel
Action-based Laravel
 
Automatyzacja utrzymania jakości w środowisku PHP
Automatyzacja utrzymania jakości w środowisku PHPAutomatyzacja utrzymania jakości w środowisku PHP
Automatyzacja utrzymania jakości w środowisku PHP
 
Wstęp do Gitlab CI/CD w aplikacjach napisanych w Laravel
Wstęp do Gitlab CI/CD w aplikacjach napisanych w LaravelWstęp do Gitlab CI/CD w aplikacjach napisanych w Laravel
Wstęp do Gitlab CI/CD w aplikacjach napisanych w Laravel
 

Recently uploaded

How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Mobile app Development Services | Drona Infotech
Mobile app Development Services  | Drona InfotechMobile app Development Services  | Drona Infotech
Mobile app Development Services | Drona Infotech
Drona Infotech
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 

Recently uploaded (20)

How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Mobile app Development Services | Drona Infotech
Mobile app Development Services  | Drona InfotechMobile app Development Services  | Drona Infotech
Mobile app Development Services | Drona Infotech
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 

Wykorzystanie form request przy implementacji API w Laravelu

  • 1. Wykorzystanie Form Request przy implementacji API w Laravelu
  • 2. Marek Tenus Full-stack Senior Developer marek@highsolutions.pl
  • 3. #1 - Architektura projektu ● NativeScript ● Angular ● TypeScript ● CSS (NativeScript) ● HTML (NativeScript)
  • 4. #1 - Architektura projektu ● PHP 7.1 ● MySQL 5.7 ● Laravel 5.5
  • 5. #1 - Architektura projektu ● PHP 7.1 ● MySQL 5.7 ● Laravel 5.5 ● CSS3 ● HTML5 ● JavaScript
  • 8. #2 - Konstrukcja API DB Client
  • 9. #2 - Konstrukcja API DB Client Server
  • 13. #2 - Konstrukcja API Client ● Send request ● Get response
  • 14. #2 - Konstrukcja API Server ● Get request ● Handle request ● Return response
  • 15. #2 - Konstrukcja API Auth/Token request / HTTPS (POST/GET/DELETE/PUT)
  • 16. #2 - Konstrukcja API request / HTTPS (POST/GET/DELETE/PUT) /api/article/1 REST Interface Auth/Token
  • 17. #2 - Konstrukcja API reponse / JSON
  • 18. #3 - Klasyczna obsługa żądań Routes
  • 19. #3 - Klasyczna obsługa żądań Routes /api/article GET index /api/article POST store
  • 20. #3 - Klasyczna obsługa żądań Routes Middleware /api/article GET index /api/article POST store
  • 21. #3 - Klasyczna obsługa żądań Routes Middleware /api/article GET index /api/article POST store allow or deny
  • 22. #3 - Klasyczna obsługa żądań Routes Middleware Controller /api/article GET index /api/article POST store allow or deny
  • 23. #3 - Klasyczna obsługa żądań Routes Middleware Controller /api/article GET index /api/article POST store allow or deny get request handle request do some stuff return response
  • 24. #3 - Klasyczna obsługa żądań Routes Middleware Controller /api/article GET index /api/article POST store allow or deny get request handle request do some stuff return response
  • 25. #3 - Klasyczna obsługa żądań namespace AppHttpControllersEventController; use AppHttpControllersController; use IlluminateHttpRequest; class EventController extends Controller { }
  • 26. #3 - Klasyczna obsługa żądań namespace AppHttpControllersEventController; use AppHttpControllersController; use IlluminateHttpRequest; class EventController extends Controller { }
  • 27. #3 - Klasyczna obsługa żądań public function __construct() {} public function index() {} //GET public function create() {} //GET public function store() {} //POST public function edit() {} //GET public function update() {} //PUT/PATCH public function destroy() {} //DELETE
  • 28. #3 - Klasyczna obsługa żądań public function store(Request $request) { }
  • 29. #3 - Klasyczna obsługa żądań public function store(Request $request) { } Dependency Injection
  • 30. #3 - Klasyczna obsługa żądań public function store() { $request = request(); }
  • 31. #3 - Klasyczna obsługa żądań public function store() { $request = request(); } Current instance of Request
  • 32. #3 - Klasyczna obsługa żądań public function store(Request $request) { //authorize the request access(?) //check if the request has valid data //store the event member //give some response }
  • 33. #3 - Klasyczna obsługa żądań //authorize the request access(?) abort_if(!$request->ajax(), 403); //check if request has valid data $request->validate([ 'first_name' => 'required|max:191', 'last_name' => 'required|max:191', 'department_id' => 'required|exists:departments,id', 'note' => 'max:512', ]); //store the event member EventMember::create($request->all()); //give some response return [ ‘success’ => true, ];
  • 34. #4 - Form Request ● Klasa dziedzicząca z klasy Request ● Posiada wbudowaną logikę walidacji ● Autoryzacja dostępu do wykonania żądania ● Czy pozwala na więcej?!
  • 35. #4 - Form Request Routes Middleware Controller /api/article GET index /api/article POST store allow or deny get request handle request do some stuff return response
  • 36. #4 - Form Request Routes Middleware Controller /api/article GET index /api/article POST store allow or deny get request do some stuff return response Form Request handle request - validation - authorization
  • 37. #4 - Form Request Routes Middleware Controller /api/article GET index /api/article POST store allow or deny get request do some stuff return response Form Request handle request - validation - authorization
  • 38. #4 - Form Request php artisan make:request StoreEventMemberRequest
  • 39. #4 - Form Request namespace AppHttpRequests; use IlluminateFoundationHttpFormRequest; class StoreEventMemberRequest extends FormRequest { public function authorize() { return false; } public function rules() { return [ ]; } }
  • 40. #4 - Form Request class StoreEventMemberRequest extends FormRequest { public function authorize() { return true; } public function rules() { return [ ]; } }
  • 41. #4 - Form Request class StoreEventMemberRequest extends FormRequest { public function authorize() { return true; } }
  • 42. #4 - Form Request class StoreEventMemberRequest extends FormRequest { public function authorize() { return $this->ajax(); } } true => access false => 403
  • 43. #4 - Form Request class StoreEventMemberRequest extends FormRequest { public function authorize() { return $this->ajax(); } } protected function failedAuthorization() { throw new HttpResponseException($this->forbiddenResponse()); } true => access false => 403
  • 44. #4 - Form Request class StoreEventMemberRequest extends FormRequest { public function authorize() { return true; } public function rules() { return [ 'first_name' => 'required|max:191', 'last_name' => 'required|max:191', 'department_id' => 'required|exists:departments,id', 'note' => 'max:512', ]; } }
  • 45. #4 - Form Request public function messages() { return [ ‘first_name.required’ => ‘Your first name is required’, ‘last_name.required’ => ‘Your last name is required’, ]; }
  • 46. #4 - Form Request public function attributes() { return [ ‘first_name’ => ‘Your first name’, ‘last_name’ => ‘Your last name’, ]; }
  • 47. #4 - Form Request public function withValidator($validator) { $validator->after(function ($validator) { if ($this->somethingElseIsInvalid()) { $validator->errors()->add('field', 'Something is wrong with this field!'); } }); }
  • 48. #4 - Form Request use AppHttpControllersController; use IlluminateHttpRequest; use AppHttpRequestsStoreEventMemberRequest; class EventController extends Controller { }
  • 49. #4 - Form Request public function store(StoreEventMemberRequest $request) { //authorize the request access(?) //check if request has valid data //store the event member //give some response }
  • 50. #4 - Form Request //authorize the request access(?) abort_if(!$request->ajax(), 403); //check if request has valid data $request->validate([ 'first_name' => 'required|max:191', 'last_name' => 'required|max:191', 'department_id' => 'required|exists:departments,id', 'note' => 'max:512', ]); //store the event member EventMember::create($request->all()); //give some response return [ ‘success’ => true, ];
  • 51. #4 - Form Request //authorize the request access(?) abort_if(!$request->ajax(), 403); //check if request has valid data $request->validate([ 'first_name' => 'required|max:191', 'last_name' => 'required|max:191', 'department_id' => 'required|exists:departments,id', 'note' => 'max:512', ]); //store the event member EventMember::create($request->all()); //give some response return [ ‘success’ => true, ];
  • 52. #4 - Form Request public function store(StoreEventMemberRequest $request) { EventMember::create($request->all()); return [ ‘success’ => true, ]; }
  • 53. #4 - Form Request
  • 54. #4 - Form Request Czy pozwala na więcej?!
  • 55. #4 - Form Request ● Oczyszczanie danych formularza (sanitizing) ● Manipulacja danymi formularza (handling) ● Logowanie zdarzeń (logging)
  • 56. #5 - Zastosowanie Form Request w projekcie ● Oczyszczanie danych formularza (sanitizing) ● Manipulacja danymi formularza (handling) ● Logowanie zdarzeń (logging)
  • 57. #5 - Zastosowanie Form Request w projekcie public function all() { }
  • 58. #5 - Zastosowanie Form Request w projekcie public function all() { $attributes = parent::all(); return collect($attributes) ->map(function($field) { return $field ?? filter_var($field, FILTER_SANITIZE_STRING); }) ->all(); }
  • 59. #5 - Zastosowanie Form Request w projekcie public function all() { $attributes = parent::all(); return collect($attributes) ->map(function($field) { return $field ?? filter_var($field, FILTER_SANITIZE_STRING); }) ->all(); } $_POST[‘data’] = [...]; 422 (Unprocessable Entity)
  • 60. #5 - Zastosowanie Form Request w projekcie public function all() { $attributes = parent::all(); return collect($attributes) ->map(function($field) { return $field ?? filter_var($field, FILTER_SANITIZE_STRING); }) ->all(); } $_POST[‘data’] = [...]; 422 (Unprocessable Entity) public function response(array $errors) { if ($this->ajax() || $this->wantsJson()) { return new JsonResponse($errors, 422); } return $this->redirector->to($this->getRedirectUrl()) ->withInput($this->except($this->dontFlash)) ->withErrors($errors, $this->errorBag); }
  • 61. #5 - Zastosowanie Form Request w projekcie public function all() { $attributes = parent::all(); return $this->sanitizeAttributes($attributes); } $_POST[‘data’] = [...]; protected function sanitizeAttributes($attributes) { return collect($attributes) ->map(function($field) { return $field ?? filter_var($field, FILTER_SANITIZE_STRING); }) ->all(); }
  • 62. #5 - Zastosowanie Form Request w projekcie public function all() { $attributes = $this->input('data'); $attributes['token'] = $this->input('token'); return $this->sanitizeAttributes($attributes); }
  • 63. #5 - Zastosowanie Form Request w projekcie public function all() { return $this->sanitizeAttributes($this->handleAttributes()); } protected function handleAttributes() { $attributes = $this->input('data'); $attributes['token'] = $this- >input('token'); return $attributes; }
  • 64. #5 - Zastosowanie Form Request w projekcie public function all() { return $this->sanitizeAttributes($this->handleAttributes()); } protected function handleAttributes() { if(!$this->has(‘data’)) { return parent::all(); } $attributes = $this->input('data'); $attributes['token'] = $this->input('token'); return $attributes; }
  • 65. #6 - Podsumowanie Zalety ● Clean code ● Dependency Injection ● Security ● Reusability
  • 66. #6 - Podsumowanie Wady ● Łamie SRP (Single Responsibility Principle) ● Przesadne używanie Form Request

Editor's Notes

  1. wskazuje na kontroller/metoda weryfikuje sposób przesyłania danych / post, get, etc. umożliwia walidację przesyłanych zmiennych - wzorce tworzenie nazw routów -> generowanie urli
  2. Middleware - warstwa aplikacji, która jest odpowiedzialna za filtrowanie żądania HTTP, middleware może również być wykorzystywany przy response dodanie nagłówków logowanie zdarzeń wskazanie middleware w routes
  3. handle request - validation, auth, do some stuff
  4. routes + middleware = mur obronny ale skupmy się na kontrolerze
  5. REST API schema
  6. Wstrzykiwanie zależności (ang. Dependency Injection, DI) – wzorzec projektowy i wzorzec architektury oprogramowania polegający na usuwaniu bezpośrednich zależności pomiędzy komponentami na rzecz architektury typu plug-in. Polega na przekazywaniu gotowych, utworzonych instancji obiektów udostępniających swoje metody i właściwości obiektom, które z nich korzystają (np. jako parametry konstruktora). Stanowi alternatywę do podejścia, gdzie obiekty tworzą instancję obiektów, z których korzystają np. we własnym konstruktorze.
  7. Posiada wbudowaną logikę walidacji ustalanie reguł tworzenie custom rules tworzenie custom messages on fail tworzenie custom response on fail
  8. form request - ma właściwości middleware i przejmuje zadanie kontrollera
  9. Determine if the user is authorized to make this request
  10. Determine if the user is authorized to make this request
  11. Determine if the user is authorized to make this request
  12. Adding After Hooks To Form Requests
  13. tu również pokazać, że mogłaby być dodatkowa weryfikacja, czy user może wykonać daną akcję, czy zapytanie jest ajaxowe etc.
  14. tak wygląda kod bez form request
  15. kod po zastosowaniu form request
  16. czy możemy zastosować form request do czegoś jeszcze? pytanie do słuchaczy
  17. czy możemy zastosować form request do czegoś jeszcze? pytanie do słuchaczy
  18. metoda Request all()
  19. FILTER_SANITIZE_STRING = Strip tags, optionally strip or encode special characters
  20. The server understands the content type of the request entity (hence a 415 Unsupported Media Type status code is inappropriate), and the syntax of the request entity is correct (thus a 400 Bad Request status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
  21. Clean code: mniej kodu, rozdzielenie metod SRP (Zasada jednej odpowiedzialności) Klasa powinna mieć tylko jedną odpowiedzialność (nigdy nie powinien istnieć więcej niż jeden powód do modyfikacji klasy).
  22. Clean code: mniej kodu, rozdzielenie metod SRP (Zasada jednej odpowiedzialności) Klasa powinna mieć tylko jedną odpowiedzialność (nigdy nie powinien istnieć więcej niż jeden powód do modyfikacji klasy).