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.
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
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)
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)