Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

of

Laravel 5 Annotations: RESTful API routing Slide 1 Laravel 5 Annotations: RESTful API routing Slide 2 Laravel 5 Annotations: RESTful API routing Slide 3 Laravel 5 Annotations: RESTful API routing Slide 4 Laravel 5 Annotations: RESTful API routing Slide 5 Laravel 5 Annotations: RESTful API routing Slide 6 Laravel 5 Annotations: RESTful API routing Slide 7 Laravel 5 Annotations: RESTful API routing Slide 8 Laravel 5 Annotations: RESTful API routing Slide 9 Laravel 5 Annotations: RESTful API routing Slide 10 Laravel 5 Annotations: RESTful API routing Slide 11 Laravel 5 Annotations: RESTful API routing Slide 12 Laravel 5 Annotations: RESTful API routing Slide 13 Laravel 5 Annotations: RESTful API routing Slide 14 Laravel 5 Annotations: RESTful API routing Slide 15 Laravel 5 Annotations: RESTful API routing Slide 16 Laravel 5 Annotations: RESTful API routing Slide 17 Laravel 5 Annotations: RESTful API routing Slide 18 Laravel 5 Annotations: RESTful API routing Slide 19 Laravel 5 Annotations: RESTful API routing Slide 20 Laravel 5 Annotations: RESTful API routing Slide 21 Laravel 5 Annotations: RESTful API routing Slide 22 Laravel 5 Annotations: RESTful API routing Slide 23 Laravel 5 Annotations: RESTful API routing Slide 24 Laravel 5 Annotations: RESTful API routing Slide 25 Laravel 5 Annotations: RESTful API routing Slide 26 Laravel 5 Annotations: RESTful API routing Slide 27 Laravel 5 Annotations: RESTful API routing Slide 28 Laravel 5 Annotations: RESTful API routing Slide 29 Laravel 5 Annotations: RESTful API routing Slide 30 Laravel 5 Annotations: RESTful API routing Slide 31 Laravel 5 Annotations: RESTful API routing Slide 32 Laravel 5 Annotations: RESTful API routing Slide 33 Laravel 5 Annotations: RESTful API routing Slide 34 Laravel 5 Annotations: RESTful API routing Slide 35 Laravel 5 Annotations: RESTful API routing Slide 36 Laravel 5 Annotations: RESTful API routing Slide 37 Laravel 5 Annotations: RESTful API routing Slide 38 Laravel 5 Annotations: RESTful API routing Slide 39 Laravel 5 Annotations: RESTful API routing Slide 40 Laravel 5 Annotations: RESTful API routing Slide 41 Laravel 5 Annotations: RESTful API routing Slide 42 Laravel 5 Annotations: RESTful API routing Slide 43 Laravel 5 Annotations: RESTful API routing Slide 44 Laravel 5 Annotations: RESTful API routing Slide 45 Laravel 5 Annotations: RESTful API routing Slide 46 Laravel 5 Annotations: RESTful API routing Slide 47 Laravel 5 Annotations: RESTful API routing Slide 48 Laravel 5 Annotations: RESTful API routing Slide 49 Laravel 5 Annotations: RESTful API routing Slide 50 Laravel 5 Annotations: RESTful API routing Slide 51 Laravel 5 Annotations: RESTful API routing Slide 52 Laravel 5 Annotations: RESTful API routing Slide 53 Laravel 5 Annotations: RESTful API routing Slide 54 Laravel 5 Annotations: RESTful API routing Slide 55 Laravel 5 Annotations: RESTful API routing Slide 56 Laravel 5 Annotations: RESTful API routing Slide 57
Upcoming SlideShare
REST APIs in Laravel 101
Next
Download to read offline and view in fullscreen.

40 Likes

Share

Download to read offline

Laravel 5 Annotations: RESTful API routing

Download to read offline

Handling RESTful API requests with Laravel PHP Framework resource controllers is already very easy. With Laravel 5, handling request routing has been made even easier by using a configuration-as-annotation approach. Controller annotations may take advantage of doc block-style syntax and then be compiled using Laravel's artisan command-line tool. I'll present this approach by providing a few examples and discussing some of the pros and cons.

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all

Laravel 5 Annotations: RESTful API routing

  1. 1. /** * @Building("RESTful APIs", in Laravel 5: * Doc Block Controller Annotations) * * @author: Christopher Pecoraro */ PHP UK Conference 2015
  2. 2. <?= 'About me' ?> $I->usePHPSince('2001'); $I->wasBornIn('Pittsburgh, Pennsylvania'); $I->liveIn('Palermo, Italy')->since('2009');
  3. 3. Annotation An annotation is metadata… ...attached to text, image, or [other] data. -Wikipedia
  4. 4. meta + data "meta" (Greek): transcending, encompassing "data" (Latin): pieces of information
  5. 5. the amanuensis 1200 C.E. Benedictine monks Annotations the Real World
  6. 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. 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. 8. Behat /** * @BeforeSuite */ public static function prepare(SuiteEvent $event) { // prepare system for test suite // before it runs } Doc-Block Annotations
  9. 9. Annotations in PHP Frameworks Zend Symfony Typo3 TDD/BDD Behat PHPUnit ORM Doctrine
  10. 10. For more details, check out: "Annotations in PHP, They exist" Rafael Dohms http://doh.ms/talk/list
  11. 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
  12. 12. Laravel 5.0 Released February 4th, 2015
  13. 13. Laravel version 4.2 /app /commands /config /controllers /database /models /storage /tests routes.php
  14. 14. 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
  15. 15. version 4.2 /app /commands /config /controllers /database /models /storage /tests routes.php Laravel version 5.0.3 /app /Http /controllers routes.php
  16. 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. 17. Route Annotations in Laravel "...an experiment in framework- agnostic controllers." -Taylor Otwell
  18. 18. Maintains Laravel components removed from the core framework: ■ Route & Event Annotations ■ Form & HTML Builder ■ The Remote (SSH) Component
  19. 19. 1. Require package via composer. Installation Procedure $ composer require laravelcollective/annotations
  20. 20. 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 = [];
  21. 21. 3. Add AnnotationsServiceProvider.php to config/app.php Installation Procedure 'providers' => [ // ... 'AppProvidersAnnotationsServiceProvider' ];
  22. 22. User Story: As a hotel website user, I want to search for a hotel so that I can reserve a room.
  23. 23. 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
  24. 24. RESTful API creation in a nutshell $ php artisan make:controller HotelsController 1: Create a hotel controller.
  25. 25. RESTful API creation in a nutshell 2: Add controller to annotation service provider's routes. protected $scanRoutes = [ 'AppHttpControllersHomeController', 'AppHttpControllersHotelsController' ];
  26. 26. 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');
  27. 27. RESTful API creation in a nutshell Double quotes are required: @Resource('/hotels') @Resource("/hotels")
  28. 28. 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');
  29. 29. RESTful API creation in a nutshell $ php artisan route:scan Routes scanned! 5: Use artisan to scan routes.
  30. 30. 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
  31. 31. RESTful API creation in a nutshell storage/framework/routes.scanned.php does not get put into source code control.
  32. 32. Edit AnnotationsServiceProvider.php to scan when local. (Optional) shortcut for 'Local' protected $scanRoutes = [ 'AppHttpControllersHotelsController', ]; protected $scanWhenLocal = true;
  33. 33. 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+]']);
  34. 34. RESTful API creation in a nutshell 1. Create the ReservationsController. $ php artisan make:controller ReservationsController
  35. 35. 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']);
  36. 36. 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']);
  37. 37. RESTful API creation in a nutshell 4. Create the ReserveRoom command. $ php artisan make:command ReserveRoom
  38. 38. 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() { } }
  39. 39. 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) ); }
  40. 40. RESTful API creation in a nutshell 6. Create RoomWasReserved Event. $ php artisan make:event RoomWasReserved
  41. 41. <?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.
  42. 42. RESTful API creation in a nutshell 8. Create Email Sender handler for RoomWasReserved event. $ php artisan handler:event RoomReservedEmail --event=RoomWasReserved
  43. 43. 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'); ');
  44. 44. RESTful API creation in a nutshell protected $scanEvents = [ 'AppHandlersEventsRoomReservedEmail' ]; 10: add RoomReservedEmail to scanEvents array.
  45. 45. RESTful API creation in a nutshell $ php artisan event:scan Events scanned! 11: Use artisan to scan events.
  46. 46. RESTful API creation in a nutshell <?php $events->listen(array(0 => 'AppEventsRoomWasReserved', ), AppHandlersEventsRoomReservedEmail@handle'); (Output of storage/framework/events.scanned.php)
  47. 47. RESTful API creation in a nutshell storage/framework/events.scanned.php storage/framework/routes.scanned.php (Final view of scanned annotation files)
  48. 48. RESTful API creation in a nutshell Laravel 4: HTTP request Router Controller
  49. 49. RESTful API creation in a nutshell Laravel 5's command-bus + pub-sub pathway: HTTP request Router Controller Command Event Handler
  50. 50. Caveat: Laravel's route caching $ php artisan route:cache Route cache cleared! Routes cached successfully! Uses artisan to cache routes (not to scan).
  51. 51. 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.
  52. 52. Caveat: Laravel's route caching <?php app('router')->setRoutes( unserialize(base64_decode('TzozNDoiSWxsdW1pbmF0ZVxSb3V0aW5nXFd…')) ); Writes to: storage/framework/routes.php
  53. 53. 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.
  54. 54. 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)
  55. 55. Available annotations HTTP verbs: @Delete @Get @Options @Patch @Post @Put Other: @Any @Controller @Middleware @Route @Where @Resource
  • aganfrusciante

    Feb. 7, 2018
  • samkahina

    Jul. 21, 2017
  • williammdavis

    Feb. 19, 2017
  • AndrewMikhailov

    Apr. 26, 2016
  • LinShi2

    Apr. 5, 2016
  • dehboris

    Mar. 17, 2016
  • aalmenar

    Feb. 2, 2016
  • chingu94

    Jan. 26, 2016
  • yazid.jibrel

    Nov. 21, 2015
  • LiangShwujiun

    Oct. 20, 2015
  • JasonNguyen12

    Oct. 18, 2015
  • VanKhoa1

    Oct. 6, 2015
  • KeeraditBoonyalapalerd

    Sep. 23, 2015
  • ssuser2ba198

    Sep. 18, 2015
  • AlbertoMalacara

    Aug. 31, 2015
  • johnkagga

    Aug. 3, 2015
  • ivaldes

    Jul. 24, 2015
  • caoy77

    Jul. 17, 2015
  • testOscar

    Jul. 9, 2015
  • bertux89

    Jun. 26, 2015

Handling RESTful API requests with Laravel PHP Framework resource controllers is already very easy. With Laravel 5, handling request routing has been made even easier by using a configuration-as-annotation approach. Controller annotations may take advantage of doc block-style syntax and then be compiled using Laravel's artisan command-line tool. I'll present this approach by providing a few examples and discussing some of the pros and cons.

Views

Total views

17,819

On Slideshare

0

From embeds

0

Number of embeds

196

Actions

Downloads

346

Shares

0

Comments

0

Likes

40

×