SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
Validation for APIs
Good validation practises. API focused.
Kirk Bushell
Who the hell am I?
• Technical Lead for Tectonic Digital (www.tectonic.com.au)
• Software architect for http://awardforce.com
• Technical writer (see: http://kirkbushell.me)
• Open source contributor (Laravel 3/4, various other projects)
• http://github.com/kirkbushell
• Also known as Oddman on IRC, forums.etc.
• @kirkbushell
Disclaimers
This is my first talk.
Sorry.
In addition...
• I'll assume you know a couple of things about validation and
• You know or at least understand some of the concepts of Laravel
4, including:
• Dependency injection and
• The IoC feature
• I start work at 4.30am (apologies if I'm not quite with it)
Why?
• There's been a lot of talk in the community the last 6 months
about validation
• How we can do it well - lots of different opinions
• I have a pretty strong opinion on this matter
What we're going to cover
• A brief history of MVC, the repository pattern and why validation
should be its own domain
• Implementing validation within an API context
• Using exceptions for greater readability
• Catching exceptions to generate API responses automagically
• The end result - cleaner code
What I'm not going to talk about
• RESTful APIs
• The view layer
A brief history of everything MVC.
• A blessing to web development (and software development in
general)
• Fat controllers, skinny models
• Skinny controllers, fat models
• Validation tied up in models (along with everything else)
• We still seem to be stuck on the previous point.
Introducing.. the repository pattern?
• Helped clean up models
• Query building and object management
• So, what about validation?
Validate all the things!
• Validation within models breaks the single responsibility principle
• Validation in models doesn't make much sense if you're using the
repository pattern
• Implemented via the controller or a service (such as a user
registration service)
Implementing validation
The validate method
Please read Jason Lewis' article: http://jasonlewis.me/article/laravel-
advanced-validation
// Validate function from article
protected function validate()
{
$this->validator = Validator::make($this->input, $this->rules);
if ($this->validator->fails())
{
throw new ValidateException($this->validator);
}
}
ValidateException
class ValidateException extends Exception
{
protected $validator;
public function __construct(Validator $validator)
{
$this->message = 'Validation has failed, or something.';
$this->validator = $validator;
}
public function getErrors()
{
return $this->validator->messages();
}
}
Our code, our rules
Implement our own custom rules for user registration:
// UserValidator class
class UserValidator extends Validator
{
public function register()
{
$this->rules = [
'email' => ['required', 'email'],
'password' => ['required']
];
$this->validate();
}
}
Validate!
Within our controller, load up our validator and validate the input.
// UserController
public function postRegister()
{
$input = Input::get();
App::make('UserValidator', [$input])->register();
return User::create($input);
}
Now what?
• When validation fails it will throw an exception:
if ($this->validator->fails())
{
throw new ValidateException($this->validator);
}
• We need to catch that exception and return a nice status code and
error message, along with any validation errors.
• Laravel 4 provides an excellent way of managing this.
Laravel 4 error handling
Create an error handler that is specific to validation exceptions:
App::error(function(ValidateException $exception)
{
$errorResponse = [
'message' => $exception->getMessage(),
'errors' => $exception->getErrors()
];
return Response::json($errorResponse, 422); // Unprocessable entity
});
In conclusion
• Complex validation should be in its own domain
• Helps to clean up our code, making it more readable
• Let the framework handle exceptions for you!
• Best for large applications (not so applicable to small apps)
Thank you.
You can catch me at the following online
locales:
• http://kirkbushell.me
• http://github.com/kirkbushell
• @kirkbushell

Mais conteúdo relacionado

Mais procurados

Automated Acceptance Tests in .NET
Automated Acceptance Tests in .NETAutomated Acceptance Tests in .NET
Automated Acceptance Tests in .NETWyn B. Van Devanter
 
Test Your Own Stuff - Scrum Atlanta 2015
Test Your Own Stuff - Scrum Atlanta 2015Test Your Own Stuff - Scrum Atlanta 2015
Test Your Own Stuff - Scrum Atlanta 2015Alex Kell
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choicetoddbr
 
How to make your functional tests really quick
How to make your functional tests really quickHow to make your functional tests really quick
How to make your functional tests really quickMikalai Alimenkou
 
BDD with SpecFlow and Selenium
BDD with SpecFlow and SeleniumBDD with SpecFlow and Selenium
BDD with SpecFlow and SeleniumLiraz Shay
 
Better End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using ProtractorBetter End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using ProtractorKasun Kodagoda
 
Practical Tips & Tricks for Selenium Test Automation
Practical Tips & Tricks for Selenium Test AutomationPractical Tips & Tricks for Selenium Test Automation
Practical Tips & Tricks for Selenium Test AutomationSauce Labs
 
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...Sargis Sargsyan
 
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...Applitools
 
How to Use Selenium, Successfully
How to Use Selenium, SuccessfullyHow to Use Selenium, Successfully
How to Use Selenium, SuccessfullySauce Labs
 
Cypress - Best Practices
Cypress - Best PracticesCypress - Best Practices
Cypress - Best PracticesBrian Mann
 
Introduction to cypress in Angular (Chinese)
Introduction to cypress in Angular (Chinese)Introduction to cypress in Angular (Chinese)
Introduction to cypress in Angular (Chinese)Hong Tat Yew
 
Selenium Tips & Tricks
Selenium Tips & TricksSelenium Tips & Tricks
Selenium Tips & TricksDave Haeffner
 
Beyond the Release: CI That Transforms Organizations
Beyond the Release: CI That Transforms OrganizationsBeyond the Release: CI That Transforms Organizations
Beyond the Release: CI That Transforms OrganizationsSauce Labs
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScriptSimon Guest
 
Web automation with Selenium for software engineers
Web automation with Selenium for software engineersWeb automation with Selenium for software engineers
Web automation with Selenium for software engineersMikalai Alimenkou
 

Mais procurados (20)

Automated Acceptance Tests in .NET
Automated Acceptance Tests in .NETAutomated Acceptance Tests in .NET
Automated Acceptance Tests in .NET
 
Agile Testing
Agile TestingAgile Testing
Agile Testing
 
Test Your Own Stuff - Scrum Atlanta 2015
Test Your Own Stuff - Scrum Atlanta 2015Test Your Own Stuff - Scrum Atlanta 2015
Test Your Own Stuff - Scrum Atlanta 2015
 
BDD for APIs
BDD for APIsBDD for APIs
BDD for APIs
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choice
 
How to make your functional tests really quick
How to make your functional tests really quickHow to make your functional tests really quick
How to make your functional tests really quick
 
BDD with SpecFlow and Selenium
BDD with SpecFlow and SeleniumBDD with SpecFlow and Selenium
BDD with SpecFlow and Selenium
 
Better End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using ProtractorBetter End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using Protractor
 
Practical Tips & Tricks for Selenium Test Automation
Practical Tips & Tricks for Selenium Test AutomationPractical Tips & Tricks for Selenium Test Automation
Practical Tips & Tricks for Selenium Test Automation
 
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
 
Cypress workshop for JSFoo 2019
Cypress  workshop for JSFoo 2019Cypress  workshop for JSFoo 2019
Cypress workshop for JSFoo 2019
 
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
 
How to Use Selenium, Successfully
How to Use Selenium, SuccessfullyHow to Use Selenium, Successfully
How to Use Selenium, Successfully
 
Cypress - Best Practices
Cypress - Best PracticesCypress - Best Practices
Cypress - Best Practices
 
Introduction to cypress in Angular (Chinese)
Introduction to cypress in Angular (Chinese)Introduction to cypress in Angular (Chinese)
Introduction to cypress in Angular (Chinese)
 
Selenium Tips & Tricks
Selenium Tips & TricksSelenium Tips & Tricks
Selenium Tips & Tricks
 
Beyond the Release: CI That Transforms Organizations
Beyond the Release: CI That Transforms OrganizationsBeyond the Release: CI That Transforms Organizations
Beyond the Release: CI That Transforms Organizations
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
 
Web automation with Selenium for software engineers
Web automation with Selenium for software engineersWeb automation with Selenium for software engineers
Web automation with Selenium for software engineers
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 

Destaque

Repository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir PoudelRepository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir PoudelSameer Poudel
 
Нюансы создания интернет-магазина на WordPress
Нюансы создания интернет-магазина на WordPressНюансы создания интернет-магазина на WordPress
Нюансы создания интернет-магазина на WordPressWordCamp Kyiv
 
WordPress: SEO. Ловим на живца.
WordPress: SEO. Ловим на живца.WordPress: SEO. Ловим на живца.
WordPress: SEO. Ловим на живца.Pavel Karpov
 
Ведение бизнеса на основе WordPress
Ведение бизнеса на основе WordPressВедение бизнеса на основе WordPress
Ведение бизнеса на основе WordPressAndrey Ovsyannikov
 
Object Oriented Design Principles
Object Oriented Design PrinciplesObject Oriented Design Principles
Object Oriented Design PrinciplesThang Tran Duc
 

Destaque (6)

WordPress: SEO
WordPress: SEOWordPress: SEO
WordPress: SEO
 
Repository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir PoudelRepository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir Poudel
 
Нюансы создания интернет-магазина на WordPress
Нюансы создания интернет-магазина на WordPressНюансы создания интернет-магазина на WordPress
Нюансы создания интернет-магазина на WordPress
 
WordPress: SEO. Ловим на живца.
WordPress: SEO. Ловим на живца.WordPress: SEO. Ловим на живца.
WordPress: SEO. Ловим на живца.
 
Ведение бизнеса на основе WordPress
Ведение бизнеса на основе WordPressВедение бизнеса на основе WordPress
Ведение бизнеса на основе WordPress
 
Object Oriented Design Principles
Object Oriented Design PrinciplesObject Oriented Design Principles
Object Oriented Design Principles
 

Semelhante a Validation for APIs in Laravel 4

Build Great Triggers Quickly with STP (the Simple Trigger Pattern)
Build Great Triggers Quickly with STP (the Simple Trigger Pattern)Build Great Triggers Quickly with STP (the Simple Trigger Pattern)
Build Great Triggers Quickly with STP (the Simple Trigger Pattern)Vivek Chawla
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Getting Started with Test-Driven Development at PHPtek 2023
Getting Started with Test-Driven Development at PHPtek 2023Getting Started with Test-Driven Development at PHPtek 2023
Getting Started with Test-Driven Development at PHPtek 2023Scott Keck-Warren
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Dinis Cruz
 
Cerberus : Framework for Manual and Automated Testing (Web Application)
Cerberus : Framework for Manual and Automated Testing (Web Application)Cerberus : Framework for Manual and Automated Testing (Web Application)
Cerberus : Framework for Manual and Automated Testing (Web Application)CIVEL Benoit
 
Cerberus_Presentation1
Cerberus_Presentation1Cerberus_Presentation1
Cerberus_Presentation1CIVEL Benoit
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
 
Comprehensive Validation with Laravel 4
Comprehensive Validation with Laravel 4Comprehensive Validation with Laravel 4
Comprehensive Validation with Laravel 4Kirk Bushell
 
Bridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous DeliveryBridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous Deliverymasoodjan
 
DefCore: The Interoperability Standard for OpenStack
DefCore: The Interoperability Standard for OpenStackDefCore: The Interoperability Standard for OpenStack
DefCore: The Interoperability Standard for OpenStackMark Voelker
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIwajrcs
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...seleniumconf
 
InteropWG Intro & Vertical Programs (May. 2017)
InteropWG Intro & Vertical Programs (May. 2017)InteropWG Intro & Vertical Programs (May. 2017)
InteropWG Intro & Vertical Programs (May. 2017)Mark Voelker
 
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)Vivek Chawla
 
Five Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can UseFive Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can UseSalesforce Developers
 
Helpful Automation Techniques - Selenium Camp 2014
Helpful Automation Techniques - Selenium Camp 2014Helpful Automation Techniques - Selenium Camp 2014
Helpful Automation Techniques - Selenium Camp 2014Justin Ison
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with SeleniumDave Haeffner
 

Semelhante a Validation for APIs in Laravel 4 (20)

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Build Great Triggers Quickly with STP (the Simple Trigger Pattern)
Build Great Triggers Quickly with STP (the Simple Trigger Pattern)Build Great Triggers Quickly with STP (the Simple Trigger Pattern)
Build Great Triggers Quickly with STP (the Simple Trigger Pattern)
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Getting Started with Test-Driven Development at PHPtek 2023
Getting Started with Test-Driven Development at PHPtek 2023Getting Started with Test-Driven Development at PHPtek 2023
Getting Started with Test-Driven Development at PHPtek 2023
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
 
Cerberus : Framework for Manual and Automated Testing (Web Application)
Cerberus : Framework for Manual and Automated Testing (Web Application)Cerberus : Framework for Manual and Automated Testing (Web Application)
Cerberus : Framework for Manual and Automated Testing (Web Application)
 
Cerberus_Presentation1
Cerberus_Presentation1Cerberus_Presentation1
Cerberus_Presentation1
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Comprehensive Validation with Laravel 4
Comprehensive Validation with Laravel 4Comprehensive Validation with Laravel 4
Comprehensive Validation with Laravel 4
 
Bridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous DeliveryBridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous Delivery
 
DefCore: The Interoperability Standard for OpenStack
DefCore: The Interoperability Standard for OpenStackDefCore: The Interoperability Standard for OpenStack
DefCore: The Interoperability Standard for OpenStack
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
 
InteropWG Intro & Vertical Programs (May. 2017)
InteropWG Intro & Vertical Programs (May. 2017)InteropWG Intro & Vertical Programs (May. 2017)
InteropWG Intro & Vertical Programs (May. 2017)
 
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
 
Five Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can UseFive Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can Use
 
Helpful Automation Techniques - Selenium Camp 2014
Helpful Automation Techniques - Selenium Camp 2014Helpful Automation Techniques - Selenium Camp 2014
Helpful Automation Techniques - Selenium Camp 2014
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
 

Último

MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 

Último (20)

MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 

Validation for APIs in Laravel 4

  • 1. Validation for APIs Good validation practises. API focused. Kirk Bushell
  • 2. Who the hell am I? • Technical Lead for Tectonic Digital (www.tectonic.com.au) • Software architect for http://awardforce.com • Technical writer (see: http://kirkbushell.me) • Open source contributor (Laravel 3/4, various other projects) • http://github.com/kirkbushell • Also known as Oddman on IRC, forums.etc. • @kirkbushell
  • 4. This is my first talk.
  • 6. In addition... • I'll assume you know a couple of things about validation and • You know or at least understand some of the concepts of Laravel 4, including: • Dependency injection and • The IoC feature • I start work at 4.30am (apologies if I'm not quite with it)
  • 7. Why? • There's been a lot of talk in the community the last 6 months about validation • How we can do it well - lots of different opinions • I have a pretty strong opinion on this matter
  • 8. What we're going to cover • A brief history of MVC, the repository pattern and why validation should be its own domain • Implementing validation within an API context • Using exceptions for greater readability • Catching exceptions to generate API responses automagically • The end result - cleaner code
  • 9. What I'm not going to talk about • RESTful APIs • The view layer
  • 10. A brief history of everything MVC. • A blessing to web development (and software development in general) • Fat controllers, skinny models • Skinny controllers, fat models • Validation tied up in models (along with everything else) • We still seem to be stuck on the previous point.
  • 11. Introducing.. the repository pattern? • Helped clean up models • Query building and object management • So, what about validation?
  • 12. Validate all the things! • Validation within models breaks the single responsibility principle • Validation in models doesn't make much sense if you're using the repository pattern • Implemented via the controller or a service (such as a user registration service)
  • 14. The validate method Please read Jason Lewis' article: http://jasonlewis.me/article/laravel- advanced-validation // Validate function from article protected function validate() { $this->validator = Validator::make($this->input, $this->rules); if ($this->validator->fails()) { throw new ValidateException($this->validator); } }
  • 15. ValidateException class ValidateException extends Exception { protected $validator; public function __construct(Validator $validator) { $this->message = 'Validation has failed, or something.'; $this->validator = $validator; } public function getErrors() { return $this->validator->messages(); } }
  • 16. Our code, our rules Implement our own custom rules for user registration: // UserValidator class class UserValidator extends Validator { public function register() { $this->rules = [ 'email' => ['required', 'email'], 'password' => ['required'] ]; $this->validate(); } }
  • 17. Validate! Within our controller, load up our validator and validate the input. // UserController public function postRegister() { $input = Input::get(); App::make('UserValidator', [$input])->register(); return User::create($input); }
  • 18. Now what? • When validation fails it will throw an exception: if ($this->validator->fails()) { throw new ValidateException($this->validator); } • We need to catch that exception and return a nice status code and error message, along with any validation errors. • Laravel 4 provides an excellent way of managing this.
  • 19. Laravel 4 error handling Create an error handler that is specific to validation exceptions: App::error(function(ValidateException $exception) { $errorResponse = [ 'message' => $exception->getMessage(), 'errors' => $exception->getErrors() ]; return Response::json($errorResponse, 422); // Unprocessable entity });
  • 20. In conclusion • Complex validation should be in its own domain • Helps to clean up our code, making it more readable • Let the framework handle exceptions for you! • Best for large applications (not so applicable to small apps)
  • 22. You can catch me at the following online locales: • http://kirkbushell.me • http://github.com/kirkbushell • @kirkbushell