SlideShare une entreprise Scribd logo
1  sur  57
Télécharger pour lire hors ligne
/**
* @Building("RESTful APIs", in Laravel 5:
* Doc Block Controller Annotations)
*
* @author: Christopher Pecoraro
*/
PHP UK Conference
2015
<?= 'About me' ?>
$I->usePHPSince('2001');
$I->wasBornIn('Pittsburgh, Pennsylvania');
$I->liveIn('Palermo, Italy')->since('2009');
Annotation
An annotation is metadata… ...attached to
text, image, or [other] data.
-Wikipedia
meta + data
"meta" (Greek): transcending, encompassing
"data" (Latin): pieces of information
the amanuensis
1200 C.E.
Benedictine monks
Annotations the Real World
Java 1.2
/**
* @author Jon Doe <jon@doe.com>
* @version 1.6 (current version number)
* @since 2010-03-31 (version package...)
*/
public void speak() {
}
Doc Block Annotations
Java 1.6
public class Animal {
public void speak() {
}
}
public class Cat extends Animal {
@Override
public void speak() {
System.out.println("Meow.");
}
}
Doc Block Annotations
Behat
/**
* @BeforeSuite
*/
public static function prepare(SuiteEvent $event)
{
// prepare system for test suite
// before it runs
}
Doc-Block Annotations
Annotations in PHP
Frameworks
Zend
Symfony
Typo3
TDD/BDD
Behat
PHPUnit
ORM
Doctrine
For more details, check out:
"Annotations in PHP, They exist"
Rafael Dohms
http://doh.ms/talk/list
Version Min. Version Release Date
4.0 PHP 5.3 May, 2013
4.1 PHP 5.3 November, 2013
4.2 PHP 5.4 (traits) May, 2014
4.3 PHP 5.4 November, 2014
Laravel
4.0 4.1 4.2 4.3 5.0
20142013
Laravel 5.0
Released February 4th, 2015
Laravel
version 4.2
/app
/commands
/config
/controllers
/database
/models
/storage
/tests
routes.php
Laravel
version 5.0.3
/app
/config
/database
/public
/storage
/tests
gulpfile.js
phpspec.yml
version 4.2
/app
/commands
/config
/controllers
/database
/models
/storage
/tests
routes.php
version 4.2
/app
/commands
/config
/controllers
/database
/models
/storage
/tests
routes.php
Laravel
version 5.0.3
/app
/Http
/controllers
routes.php
Route Annotations in Laravel
Raison d'être:
routes.php can get to be really, really, really huge.
Route::patch('hotel/{hid}/room/{rid}','HotelController@editRoom');
Route::post('hotel/{hid}/room/{rid}','HotelController@reserve');
Route::get('hotel/stats,HotelController@Stats');
Route::resource('country', 'CountryController');
Route::resource(city', 'CityController');
Route::resource('state', 'StateController');
Route::resource('amenity', 'AmenitiyController');
Route::resource('country', 'CountryController');
Route::resource(city', 'CityController');
Route::resource('country', 'CountryController');
Route::resource('city', 'CityController');
Route::resource('horse', 'HorseController');
Route::resource('cow', 'CowController');
Route::resource('zebra', 'ZebraController');
Route::get('dragon/{id}', 'DragonController@show');
Route::resource('giraffe', 'GiraffeController');
Route::resource('zebrafish', 'ZebrafishController');
Route::get('zebras/{id}', 'ZebraController@show');
Route Annotations in Laravel
"...an experiment in framework-
agnostic controllers."
-Taylor Otwell
Maintains Laravel components removed from the core framework:
■ Route & Event Annotations
■ Form & HTML Builder
■ The Remote (SSH) Component
1. Require package via composer.
Installation Procedure
$ composer require laravelcollective/annotations
2. Create AnnotationsServiceProvider.php
Installation Procedure
<?php namespace AppProviders;
use CollectiveAnnotationsAnnotationsServiceProvider as ServiceProvider;
class AnnotationsServiceProvider extends ServiceProvider {
/**
* The classes to scan for event annotations.
* @var array
*/
protected $scanEvents = [];
3. Add AnnotationsServiceProvider.php to config/app.php
Installation Procedure
'providers' => [
// ...
'AppProvidersAnnotationsServiceProvider'
];
User Story:
As a hotel website user,
I want to search for a hotel
so that I can reserve a room.
RESTful API creation in a nutshell
artisan command-line tool:
Laravel’s command line interface tool for basic
development-related tasks:
● Perform migrations
● Create resource controllers
● Many repetitious tasks
RESTful API creation in a nutshell
$ php artisan make:controller HotelsController
1: Create a hotel controller.
RESTful API creation in a nutshell
2: Add controller to annotation service provider's routes.
protected $scanRoutes = [
'AppHttpControllersHomeController',
'AppHttpControllersHotelsController'
];
RESTful API creation in a nutshell
3: Add resource annotation to hotel controller.
<?php namespace AppHttpControllers;
use ...
/**
* @Resource("/hotels")
*/
class HotelsController extends Controller {
public function index()
{
}
// Laravel 5.0 standard
Route::resource('hotels','HotelsController');
RESTful API creation in a nutshell
Double quotes are required:
@Resource('/hotels')
@Resource("/hotels")
RESTful API creation in a nutshell
4: Add search method to handle GET.
class HotelsController extends Controller {
public function index()
{
}
/**
* Search for a hotel
* @Get("/hotels/search")
*/
public function search()
{
}
// Laravel 5.0 standard
Route::get('hotels/search',HotelsController@search');
RESTful API creation in a nutshell
$ php artisan route:scan
Routes scanned!
5: Use artisan to scan routes.
RESTful API creation in a nutshell
$router->get('search', [
'uses' => 'AppHttpControllersHotelsController@search',
'as' => NULL,
'middleware' => [],
'where' => [],
'domain' => NULL,
]);
Writes to: storage/framework/routes.scanned.php
RESTful API creation in a nutshell
storage/framework/routes.scanned.php
does not get put into source code control.
Edit AnnotationsServiceProvider.php to scan when local.
(Optional) shortcut for 'Local'
protected $scanRoutes = [
'AppHttpControllersHotelsController',
];
protected $scanWhenLocal = true;
RESTful API creation in a nutshell
Show the hotel that we are interested in.
<?php namespace AppHttpControllers;
use …
/**
* @Resource("/hotels",except={"show"})
*/
class HotelsController extends Controller {
/**
* Display the specified resource.
* @Get("/hotels/{id}") // or @Get("/hotels/{id}",where={"id": "d+"})
* @Where({"id": "d+"})
*/
public function show($id)
{
}
// Laravel 5.0 standard
Route::get('hotels/{id}','HotelsController@show')
->where(['id' => '[d+]']);
RESTful API creation in a nutshell
1. Create the ReservationsController.
$ php artisan make:controller ReservationsController
RESTful API creation in a nutshell
2. Add a POST route annotation and auth Middleware.
<?php namespace AppHttpControllers;
use ...
class ReservationsController extends Controller {
/**
* @Post("/bookRoom")
* @Middleware("auth")
*/
public function reserve()
{
}
// Laravel 5.0 standard
Route::post('/bookRoom','ReservationsController@reserve',
['middleware' => 'auth']);
RESTful API creation in a nutshell
3. Limit requests to valid url.
<?php namespace AppHttpControllers;
use …
/**
* @Controller(domain="booking.hotelwebsite.com")
*/
class ReservationsController extends Controller {
/**
* @Post("/bookRoom")
* @Middleware("auth")
*/
public function reserve()
{
//Laravel 5.0 standard
Route::post('/bookRoom','ReservationsController@reserve',
['middleware' => 'auth', 'domain'=>'booking.hotelwebsite.
com']);
RESTful API creation in a nutshell
4. Create the ReserveRoom command.
$ php artisan make:command ReserveRoom
RESTful API creation in a nutshell
(Contents of the ReserveRoom Command)
<?php namespace AppCommands;
use ...
class ReserveRoom extends Command implements SelfHandling {
public function __construct()
{
}
/**
* Execute the command.
*/
public function handle()
{
}
}
RESTful API creation in a nutshell
5. Create new ReserveRoom for Reservation Controller
<?php namespace AppHttpControllers;
use ...
class ReservationsController extends Controller {
/**
* @Post("/bookRoom")
* @Middleware("auth")
*/
public function reserve()
{
$this->dispatch(
new ReserveRoom(Auth::user(),$start_date,$end_date,$rooms)
);
}
RESTful API creation in a nutshell
6. Create RoomWasReserved Event.
$ php artisan make:event RoomWasReserved
<?php namespace AppCommands;
use AppCommandsCommand;
use IlluminateContractsBusSelfHandling;
class ReserveRoom extends Command implements SelfHandling {
public function __construct(User $user, $start_date, $end_date, $rooms)
{
}
public function handle()
{
$reservation = Reservation::createNew();
event(new RoomWasReserved($reservation));
}
}
RESTful API creation in a nutshell
7. Fire RoomWasReserved event from ReserveRoom handler.
RESTful API creation in a nutshell
8. Create Email Sender handler for RoomWasReserved event.
$ php artisan handler:event RoomReservedEmail --event=RoomWasReserved
RESTful API creation in a nutshell
9. Create SendEmail handler for RoomWasReserved event.
<?php namespace AppHandlersEvents;
use ...
class RoomReservedEmail {
public function __construct()
{
}
/**
* Handle the event.
* @Hears("AppEventsRoomWasReserved")
* @param RoomWasReserved $event
*/
public function handle(RoomWasReserved $event)
{
}
}
Laravel 5.0 standard
Event::listen
('AppEventsRoomWasReserved','AppHand
lersEventsRoomReservedEmail@handle');
');
RESTful API creation in a nutshell
protected $scanEvents = [
'AppHandlersEventsRoomReservedEmail'
];
10: add RoomReservedEmail to scanEvents array.
RESTful API creation in a nutshell
$ php artisan event:scan
Events scanned!
11: Use artisan to scan events.
RESTful API creation in a nutshell
<?php $events->listen(array(0 => 'AppEventsRoomWasReserved',
), AppHandlersEventsRoomReservedEmail@handle');
(Output of storage/framework/events.scanned.php)
RESTful API creation in a nutshell
storage/framework/events.scanned.php
storage/framework/routes.scanned.php
(Final view of scanned annotation files)
RESTful API creation in a nutshell
Laravel 4:
HTTP request
Router
Controller
RESTful API creation in a nutshell
Laravel 5's command-bus + pub-sub pathway:
HTTP request
Router
Controller
Command
Event
Handler
Caveat: Laravel's route caching
$ php artisan route:cache
Route cache cleared!
Routes cached successfully!
Uses artisan to cache routes (not to scan).
Caveat: Laravel's route caching
$ php artisan route:scan
Routes scanned!
$ php artisan route:cache
Route cache cleared!
Routes cached successfully!
route:scan must be executed before route:cache.
Caveat: Laravel's route caching
<?php
app('router')->setRoutes(
unserialize(base64_decode('TzozNDoiSWxsdW1pbmF0ZVxSb3V0aW5nXFd…'))
);
Writes to: storage/framework/routes.php
Caveat: Laravel's route caching
$ php artisan route:scan
/storage/framework/routes.scanned.php
$ php artisan route:cache
/storage/framework/routes.php
Both files will be created, but only the compiled
routes.php file is used until php artisan route:
scan is run again.
RESTful API creation in a nutshell
storage/framework/events.scanned.php // scanned
storage/framework/routes.scanned.php // scanned
storage/framework/routes.php // cached, if exists, this
// will be used
(Final view of scanned and cached annotation files)
Available annotations
HTTP verbs:
@Delete
@Get
@Options
@Patch
@Post
@Put
Other:
@Any
@Controller
@Middleware
@Route
@Where
@Resource
Laravel 5 Annotations: RESTful API routing

Contenu connexe

Tendances

Laravel introduction
Laravel introductionLaravel introduction
Laravel introductionSimon Funk
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web ArtisansRaf Kewl
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Vikas Chauhan
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with LaravelMichael Peacock
 
Web service with Laravel
Web service with LaravelWeb service with Laravel
Web service with LaravelAbuzer Firdousi
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravelConfiz
 
All the Laravel things: up and running to making $$
All the Laravel things: up and running to making $$All the Laravel things: up and running to making $$
All the Laravel things: up and running to making $$Joe Ferguson
 
A introduction to Laravel framework
A introduction to Laravel frameworkA introduction to Laravel framework
A introduction to Laravel frameworkPhu Luong Trong
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5Darren Craig
 
Knowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkKnowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkBukhori Aqid
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5Soheil Khodayari
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentationToufiq Mahmud
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
All Aboard for Laravel 5.1
All Aboard for Laravel 5.1All Aboard for Laravel 5.1
All Aboard for Laravel 5.1Jason McCreary
 

Tendances (20)

Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with Laravel
 
Web service with Laravel
Web service with LaravelWeb service with Laravel
Web service with Laravel
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravel
 
All the Laravel things: up and running to making $$
All the Laravel things: up and running to making $$All the Laravel things: up and running to making $$
All the Laravel things: up and running to making $$
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Workshop Laravel 5.2
Workshop Laravel 5.2Workshop Laravel 5.2
Workshop Laravel 5.2
 
Laravel Introduction
Laravel IntroductionLaravel Introduction
Laravel Introduction
 
Laravel ppt
Laravel pptLaravel ppt
Laravel ppt
 
A introduction to Laravel framework
A introduction to Laravel frameworkA introduction to Laravel framework
A introduction to Laravel framework
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Laravel overview
Laravel overviewLaravel overview
Laravel overview
 
Knowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkKnowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP framework
 
Laravel Tutorial PPT
Laravel Tutorial PPTLaravel Tutorial PPT
Laravel Tutorial PPT
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentation
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
All Aboard for Laravel 5.1
All Aboard for Laravel 5.1All Aboard for Laravel 5.1
All Aboard for Laravel 5.1
 

En vedette

REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroChristopher Pecoraro
 
Laravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and PoliciesLaravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and PoliciesAlison Gianotto
 
Password Storage and Attacking in PHP
Password Storage and Attacking in PHPPassword Storage and Attacking in PHP
Password Storage and Attacking in PHPAnthony Ferrara
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Nicolás Bouhid
 
Security Bootcamp for Startups and Small Businesses
Security Bootcamp for Startups and Small Businesses Security Bootcamp for Startups and Small Businesses
Security Bootcamp for Startups and Small Businesses Alison Gianotto
 
Storage & Controller Trends and Outlook - August 2013
Storage & Controller Trends and Outlook - August 2013Storage & Controller Trends and Outlook - August 2013
Storage & Controller Trends and Outlook - August 2013JonCarvinzer
 
Mastering OpenStack - Episode 03 - Simple Architectures
Mastering OpenStack - Episode 03 - Simple ArchitecturesMastering OpenStack - Episode 03 - Simple Architectures
Mastering OpenStack - Episode 03 - Simple ArchitecturesRoozbeh Shafiee
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 Joe Ferguson
 
Storage Area Network
Storage Area NetworkStorage Area Network
Storage Area NetworkRaphael Ejike
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In DepthKirk Bushell
 
Storage area network
Storage area networkStorage area network
Storage area networkNeha Agarwal
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 

En vedette (20)

REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
 
Laravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and PoliciesLaravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and Policies
 
Password Storage and Attacking in PHP
Password Storage and Attacking in PHPPassword Storage and Attacking in PHP
Password Storage and Attacking in PHP
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
Javascript laravel's friend
Javascript laravel's friendJavascript laravel's friend
Javascript laravel's friend
 
Security Bootcamp for Startups and Small Businesses
Security Bootcamp for Startups and Small Businesses Security Bootcamp for Startups and Small Businesses
Security Bootcamp for Startups and Small Businesses
 
Storage & Controller Trends and Outlook - August 2013
Storage & Controller Trends and Outlook - August 2013Storage & Controller Trends and Outlook - August 2013
Storage & Controller Trends and Outlook - August 2013
 
Introduction to j_query
Introduction to j_queryIntroduction to j_query
Introduction to j_query
 
Mastering OpenStack - Episode 03 - Simple Architectures
Mastering OpenStack - Episode 03 - Simple ArchitecturesMastering OpenStack - Episode 03 - Simple Architectures
Mastering OpenStack - Episode 03 - Simple Architectures
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Presentation laravel 5 4
Presentation laravel 5 4Presentation laravel 5 4
Presentation laravel 5 4
 
Storage Area Network
Storage Area NetworkStorage Area Network
Storage Area Network
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
Storage Basics
Storage BasicsStorage Basics
Storage Basics
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
 
Storage area network
Storage area networkStorage area network
Storage area network
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 

Similaire à Laravel 5 Annotations: RESTful API routing

HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsRemy Sharp
 
2019 11-bgphp
2019 11-bgphp2019 11-bgphp
2019 11-bgphpdantleech
 
Going serverless with Fn project, Fn Flow and Kubernetes
Going serverless with Fn project, Fn Flow and KubernetesGoing serverless with Fn project, Fn Flow and Kubernetes
Going serverless with Fn project, Fn Flow and KubernetesAndy Moncsek
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationRutul Shah
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
From Ruby to Node.js
From Ruby to Node.jsFrom Ruby to Node.js
From Ruby to Node.jsjubilem
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Introduction to web and php mysql
Introduction to web and php mysqlIntroduction to web and php mysql
Introduction to web and php mysqlProgrammer Blog
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)dantleech
 
Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02arghya007
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swiftTim Burks
 
Creating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 ComponentsCreating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 ComponentsDeepak Chandani
 
Vitta Minicurso Laravel - Hackathon League of Legends
Vitta Minicurso Laravel - Hackathon League of LegendsVitta Minicurso Laravel - Hackathon League of Legends
Vitta Minicurso Laravel - Hackathon League of LegendsFilipe Forattini
 

Similaire à Laravel 5 Annotations: RESTful API routing (20)

HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & sockets
 
2019 11-bgphp
2019 11-bgphp2019 11-bgphp
2019 11-bgphp
 
Going serverless with Fn project, Fn Flow and Kubernetes
Going serverless with Fn project, Fn Flow and KubernetesGoing serverless with Fn project, Fn Flow and Kubernetes
Going serverless with Fn project, Fn Flow and Kubernetes
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integration
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
From Ruby to Node.js
From Ruby to Node.jsFrom Ruby to Node.js
From Ruby to Node.js
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
REST in Peace
REST in PeaceREST in Peace
REST in Peace
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Introduction to web and php mysql
Introduction to web and php mysqlIntroduction to web and php mysql
Introduction to web and php mysql
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
 
9. Radio1 in Laravel
9. Radio1 in Laravel 9. Radio1 in Laravel
9. Radio1 in Laravel
 
Creating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 ComponentsCreating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 Components
 
Vitta Minicurso Laravel - Hackathon League of Legends
Vitta Minicurso Laravel - Hackathon League of LegendsVitta Minicurso Laravel - Hackathon League of Legends
Vitta Minicurso Laravel - Hackathon League of Legends
 

Dernier

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 

Dernier (20)

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 

Laravel 5 Annotations: RESTful API routing

  • 1. /** * @Building("RESTful APIs", in Laravel 5: * Doc Block Controller Annotations) * * @author: Christopher Pecoraro */ PHP UK Conference 2015
  • 2. <?= 'About me' ?> $I->usePHPSince('2001'); $I->wasBornIn('Pittsburgh, Pennsylvania'); $I->liveIn('Palermo, Italy')->since('2009');
  • 3. Annotation An annotation is metadata… ...attached to text, image, or [other] data. -Wikipedia
  • 4. meta + data "meta" (Greek): transcending, encompassing "data" (Latin): pieces of information
  • 5. the amanuensis 1200 C.E. Benedictine monks Annotations the Real World
  • 6. Java 1.2 /** * @author Jon Doe <jon@doe.com> * @version 1.6 (current version number) * @since 2010-03-31 (version package...) */ public void speak() { } Doc Block Annotations
  • 7. Java 1.6 public class Animal { public void speak() { } } public class Cat extends Animal { @Override public void speak() { System.out.println("Meow."); } } Doc Block Annotations
  • 8. Behat /** * @BeforeSuite */ public static function prepare(SuiteEvent $event) { // prepare system for test suite // before it runs } Doc-Block Annotations
  • 10. For more details, check out: "Annotations in PHP, They exist" Rafael Dohms http://doh.ms/talk/list
  • 11. Version Min. Version Release Date 4.0 PHP 5.3 May, 2013 4.1 PHP 5.3 November, 2013 4.2 PHP 5.4 (traits) May, 2014 4.3 PHP 5.4 November, 2014 Laravel 4.0 4.1 4.2 4.3 5.0 20142013
  • 16. Route Annotations in Laravel Raison d'être: routes.php can get to be really, really, really huge. Route::patch('hotel/{hid}/room/{rid}','HotelController@editRoom'); Route::post('hotel/{hid}/room/{rid}','HotelController@reserve'); Route::get('hotel/stats,HotelController@Stats'); Route::resource('country', 'CountryController'); Route::resource(city', 'CityController'); Route::resource('state', 'StateController'); Route::resource('amenity', 'AmenitiyController'); Route::resource('country', 'CountryController'); Route::resource(city', 'CityController'); Route::resource('country', 'CountryController'); Route::resource('city', 'CityController'); Route::resource('horse', 'HorseController'); Route::resource('cow', 'CowController'); Route::resource('zebra', 'ZebraController'); Route::get('dragon/{id}', 'DragonController@show'); Route::resource('giraffe', 'GiraffeController'); Route::resource('zebrafish', 'ZebrafishController'); Route::get('zebras/{id}', 'ZebraController@show');
  • 17. Route Annotations in Laravel "...an experiment in framework- agnostic controllers." -Taylor Otwell
  • 18.
  • 19. Maintains Laravel components removed from the core framework: ■ Route & Event Annotations ■ Form & HTML Builder ■ The Remote (SSH) Component
  • 20. 1. Require package via composer. Installation Procedure $ composer require laravelcollective/annotations
  • 21. 2. Create AnnotationsServiceProvider.php Installation Procedure <?php namespace AppProviders; use CollectiveAnnotationsAnnotationsServiceProvider as ServiceProvider; class AnnotationsServiceProvider extends ServiceProvider { /** * The classes to scan for event annotations. * @var array */ protected $scanEvents = [];
  • 22. 3. Add AnnotationsServiceProvider.php to config/app.php Installation Procedure 'providers' => [ // ... 'AppProvidersAnnotationsServiceProvider' ];
  • 23. User Story: As a hotel website user, I want to search for a hotel so that I can reserve a room.
  • 24. RESTful API creation in a nutshell artisan command-line tool: Laravel’s command line interface tool for basic development-related tasks: ● Perform migrations ● Create resource controllers ● Many repetitious tasks
  • 25. RESTful API creation in a nutshell $ php artisan make:controller HotelsController 1: Create a hotel controller.
  • 26. RESTful API creation in a nutshell 2: Add controller to annotation service provider's routes. protected $scanRoutes = [ 'AppHttpControllersHomeController', 'AppHttpControllersHotelsController' ];
  • 27. RESTful API creation in a nutshell 3: Add resource annotation to hotel controller. <?php namespace AppHttpControllers; use ... /** * @Resource("/hotels") */ class HotelsController extends Controller { public function index() { } // Laravel 5.0 standard Route::resource('hotels','HotelsController');
  • 28. RESTful API creation in a nutshell Double quotes are required: @Resource('/hotels') @Resource("/hotels")
  • 29. RESTful API creation in a nutshell 4: Add search method to handle GET. class HotelsController extends Controller { public function index() { } /** * Search for a hotel * @Get("/hotels/search") */ public function search() { } // Laravel 5.0 standard Route::get('hotels/search',HotelsController@search');
  • 30. RESTful API creation in a nutshell $ php artisan route:scan Routes scanned! 5: Use artisan to scan routes.
  • 31. RESTful API creation in a nutshell $router->get('search', [ 'uses' => 'AppHttpControllersHotelsController@search', 'as' => NULL, 'middleware' => [], 'where' => [], 'domain' => NULL, ]); Writes to: storage/framework/routes.scanned.php
  • 32. RESTful API creation in a nutshell storage/framework/routes.scanned.php does not get put into source code control.
  • 33. Edit AnnotationsServiceProvider.php to scan when local. (Optional) shortcut for 'Local' protected $scanRoutes = [ 'AppHttpControllersHotelsController', ]; protected $scanWhenLocal = true;
  • 34. RESTful API creation in a nutshell Show the hotel that we are interested in. <?php namespace AppHttpControllers; use … /** * @Resource("/hotels",except={"show"}) */ class HotelsController extends Controller { /** * Display the specified resource. * @Get("/hotels/{id}") // or @Get("/hotels/{id}",where={"id": "d+"}) * @Where({"id": "d+"}) */ public function show($id) { } // Laravel 5.0 standard Route::get('hotels/{id}','HotelsController@show') ->where(['id' => '[d+]']);
  • 35. RESTful API creation in a nutshell 1. Create the ReservationsController. $ php artisan make:controller ReservationsController
  • 36. RESTful API creation in a nutshell 2. Add a POST route annotation and auth Middleware. <?php namespace AppHttpControllers; use ... class ReservationsController extends Controller { /** * @Post("/bookRoom") * @Middleware("auth") */ public function reserve() { } // Laravel 5.0 standard Route::post('/bookRoom','ReservationsController@reserve', ['middleware' => 'auth']);
  • 37. RESTful API creation in a nutshell 3. Limit requests to valid url. <?php namespace AppHttpControllers; use … /** * @Controller(domain="booking.hotelwebsite.com") */ class ReservationsController extends Controller { /** * @Post("/bookRoom") * @Middleware("auth") */ public function reserve() { //Laravel 5.0 standard Route::post('/bookRoom','ReservationsController@reserve', ['middleware' => 'auth', 'domain'=>'booking.hotelwebsite. com']);
  • 38. RESTful API creation in a nutshell 4. Create the ReserveRoom command. $ php artisan make:command ReserveRoom
  • 39. RESTful API creation in a nutshell (Contents of the ReserveRoom Command) <?php namespace AppCommands; use ... class ReserveRoom extends Command implements SelfHandling { public function __construct() { } /** * Execute the command. */ public function handle() { } }
  • 40. RESTful API creation in a nutshell 5. Create new ReserveRoom for Reservation Controller <?php namespace AppHttpControllers; use ... class ReservationsController extends Controller { /** * @Post("/bookRoom") * @Middleware("auth") */ public function reserve() { $this->dispatch( new ReserveRoom(Auth::user(),$start_date,$end_date,$rooms) ); }
  • 41. RESTful API creation in a nutshell 6. Create RoomWasReserved Event. $ php artisan make:event RoomWasReserved
  • 42. <?php namespace AppCommands; use AppCommandsCommand; use IlluminateContractsBusSelfHandling; class ReserveRoom extends Command implements SelfHandling { public function __construct(User $user, $start_date, $end_date, $rooms) { } public function handle() { $reservation = Reservation::createNew(); event(new RoomWasReserved($reservation)); } } RESTful API creation in a nutshell 7. Fire RoomWasReserved event from ReserveRoom handler.
  • 43. RESTful API creation in a nutshell 8. Create Email Sender handler for RoomWasReserved event. $ php artisan handler:event RoomReservedEmail --event=RoomWasReserved
  • 44. RESTful API creation in a nutshell 9. Create SendEmail handler for RoomWasReserved event. <?php namespace AppHandlersEvents; use ... class RoomReservedEmail { public function __construct() { } /** * Handle the event. * @Hears("AppEventsRoomWasReserved") * @param RoomWasReserved $event */ public function handle(RoomWasReserved $event) { } } Laravel 5.0 standard Event::listen ('AppEventsRoomWasReserved','AppHand lersEventsRoomReservedEmail@handle'); ');
  • 45. RESTful API creation in a nutshell protected $scanEvents = [ 'AppHandlersEventsRoomReservedEmail' ]; 10: add RoomReservedEmail to scanEvents array.
  • 46. RESTful API creation in a nutshell $ php artisan event:scan Events scanned! 11: Use artisan to scan events.
  • 47. RESTful API creation in a nutshell <?php $events->listen(array(0 => 'AppEventsRoomWasReserved', ), AppHandlersEventsRoomReservedEmail@handle'); (Output of storage/framework/events.scanned.php)
  • 48. RESTful API creation in a nutshell storage/framework/events.scanned.php storage/framework/routes.scanned.php (Final view of scanned annotation files)
  • 49. RESTful API creation in a nutshell Laravel 4: HTTP request Router Controller
  • 50. RESTful API creation in a nutshell Laravel 5's command-bus + pub-sub pathway: HTTP request Router Controller Command Event Handler
  • 51. Caveat: Laravel's route caching $ php artisan route:cache Route cache cleared! Routes cached successfully! Uses artisan to cache routes (not to scan).
  • 52. Caveat: Laravel's route caching $ php artisan route:scan Routes scanned! $ php artisan route:cache Route cache cleared! Routes cached successfully! route:scan must be executed before route:cache.
  • 53. Caveat: Laravel's route caching <?php app('router')->setRoutes( unserialize(base64_decode('TzozNDoiSWxsdW1pbmF0ZVxSb3V0aW5nXFd…')) ); Writes to: storage/framework/routes.php
  • 54. Caveat: Laravel's route caching $ php artisan route:scan /storage/framework/routes.scanned.php $ php artisan route:cache /storage/framework/routes.php Both files will be created, but only the compiled routes.php file is used until php artisan route: scan is run again.
  • 55. RESTful API creation in a nutshell storage/framework/events.scanned.php // scanned storage/framework/routes.scanned.php // scanned storage/framework/routes.php // cached, if exists, this // will be used (Final view of scanned and cached annotation files)