Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Intro to Laravel 5

Ben Edmunds
January 15, 2016

Intro to Laravel 5

Learn why this new framework has been taking the PHP world by storm.

Are you ashamed to admit you're a PHP developer? Have you been using the same old, boring PHP framework for years? Tired of your PHP applications turning into enormous beasts? Maybe you've heard about Laravel but haven't made the effort to dive into it? In this presentation, we'll walk through what makes Laravel an elegant, fun, and exciting framework to make PHP applications that you'll be proud of.

Ben Edmunds

January 15, 2016

More Decks by Ben Edmunds

Other Decks in Technology


  1. A PHP Framework For Web Artisans

  2. Ben Edmunds @benedmunds http://benedmunds.com Who is this guy?

  3. Ben Edmunds Open Source Author PHP Town Hall Podcast CTO

    at Mindfulware Who is this guy?
  4. What is it? PHP Web Framework Full-stack (what does that

    even mean anymore) Open Source
  5. Who’s behind it? Taylor Otwell @taylorotwell

  6. I already use X. Why should I use Laravel?

  7. Why use it? Expressive Syntax Route::get(‘user/{id}’, function($id) { $user =

    User::find($id); return view(‘home') ->with('user', $user); });
  8. Why use it? Utilizes the latest PHP features Namespaces PSR-4

    Autoloading Interfaces IoC
  9. Why use it? Service Providers De-Coupled Flexible DRY Event Handling

  10. Why use it? Contracts = Groups of Interfaces Loose Coupling

    Testability Explicit Flexible
  11. Why use it? Facades = Quick Start $object = new

    class; $object->set('key', 'value'); Class::set('key', 'value');
  12. Why use it? Well Documented http://laravel.com/docs

  13. Why use it? Artisan CLI Tool $ php artisan migrate

  14. Why use it? Built on Composer http://packagist.com Entirely Modular PSR-2,

    PSR-3, PSR-4, PSR-7 Compliant
  15. Why use it? Test Coverage Focus on Testable Code

  16. Why use it? Full Stack Framework Full Stack Ecosystem

  17. Why use it? Homestead Pre-made Vagrant Box Nginx MySQL/PostgreSQL Beanstalkd

    Redis Memcached PHP / HHVM Node
  18. Why use it? PAAS to quickly deploy PHP apps to

    the “cloud” Digital Ocean Linode AWS
  19. Let’s do some comparisons

  20. Comparison MVC Design Lightweight Fast Excellent Docs Compatibility Technical Debt

  21. Comparison MVC Design Heavy but has Silex Slow-ish Complex Good

    Docs Modular Backed by SensioLabs
  22. Beyond MVC Design Easy to get started Consistent/Stable Fast Excellent

    Docs Threw out previous framework ideas and started over Comparison
  23. OK, I’ll try it. How do I get started?

  24. Download Composer Based Install $ composer create-project laravel/laravel --prefer-dist

  25. Structure Commands Providers Controller || Route || Both Middleware Services

    Views Model / Repository / FLEXIBILITY
  26. Structure app Commands Handlers Commands Events Http Controllers Middleware Requests

    Providers Services config resources views tests app Commands Console Events Handlers Commands Events Http Controllers Middleware Requests Providers Services bootstrap config database migrations seeds public package resources lang views storage cache logs meta sessions views work tests
  27. Routes

  28. Routes Create routes at: app/Http/routes.php include() additional route definitions if

  29. Routes What methods are available: Route::get(); Route::post(); Route::put(); Route::patch(); Route::delete();

    Route::any(); //all of the above
  30. Routes Register multiple verbs for a single route: Router::match([‘get’, ‘post’],

    ‘/’, function(){ //this will run for both GET and POST });
  31. Routes app/Http/routes.php Route::get('/', function(){ echo ‘Boom!’; });

  32. Testing

  33. Testing Runs all tests located at: /tests/ $ php artisan

  34. Testing app/Http/routes.php Route::get('/', function(){ echo ‘Boom!’; });

  35. Testing /tests/ExampleTest.php Test it! Test it good! class ExampleTest extends

    TestCase { function testBasicExample() { $this->visit('/') ->see(‘Boom!');
  36. Testing $ php artisan test Run it! PHPUnit 3.6.10 by

    Sebastian Bergmann. Configuration read from ... Time: 0 seconds, Memory: 6.25Mb OK (1 test, 1 assertion) Output
  37. API?

  38. What about an API? Routes to the rescue!

  39. API app/Http/routes.php Route::get(‘api/user/{id}’, function($id){ return json_encode([ ‘user‘ => User::find($id), ‘success‘

    => true ]); });
  40. API app/Http/routes.php Route::get(‘api/user/{id}’, function($id){ return [ ‘user‘ => User::find($id), ‘success‘

    => true ]; });
  41. API /tests/api/UserTest.php class UserTest extends TestCase { public function testGetUser()

    { $this->get(‘/user/1') ->seeJson([ ‘success‘ => true ]);
  42. API Route::get(); Route::post(); Route::put(); Route::patch(); Route::delete();

  43. Controllers

  44. Controllers OK, routes are cool and all, but what if

    I want to use controllers?
  45. Controllers app/Http/routes.php Route::post('status', '[email protected]'); class StatusController extends Controller { public

    function create(Request $request) { … app/Http/controllers/StatusController.php
  46. Shit just got real

  47. Middleware

  48. Middleware Route Filters BETTER FASTER STRONGER Middleware!

  49. Middleware Popular Uses: Auth ACL Session Caching Debug Logging Analytics

    Rate Limiting
  50. Middleware Route::post('status', ‘[email protected]’, [‘middleware’ => ‘auth’] );

  51. Middleware Route::post('status', ‘[email protected]’, [‘middleware’ => [ ‘first’, ‘second’, ‘third’, ]]

  52. Middleware class AjaxMiddleware implements Middleware { public function handle($request, Closure

    $next) { if (!$request->ajax()) return response('Unauthorized.', 401); return $next($request); }
  53. Middleware Groups for DRY routing: Route::group(['middleware' => 'auth'], function(){ Route::get('/statuses',

    function(){ … }); …
  54. Database

  55. Database Query Builder Eloquent ORM Migrations Seeding

  56. Query Builder Simple and Easy to Understand Used extensively by

    Eloquent ORM
  57. Query Builder $user = DB::table('statuses') ->where(‘email’, '[email protected]’) ->first(); Query Row

    by Email
  58. Query Builder $id = DB::table('statuses') ->insertGetId([ ‘user_id' => 1, 'email'

    => ‘[email protected]', 'text' => ‘Vegas Baby! #zendcon’, ]); Insert & Get ID
  59. Eloquent ORM Simple Expressive Efficient

  60. Eloquent ORM use Illuminate\Database\Eloquent\Model; class Status extends Model { }

    Define an Eloquent model
  61. Eloquent ORM $status = App\Status::where(‘user_id’, 1) ->first(); Simple query

  62. Eloquent ORM $statuses = App\Status::where(‘views', '>', 100) ->get(); Slightly more

    advanced query
  63. Eloquent ORM Relationships class Status extends Model { public function

    user() { return $this->belongsTo(‘App\User'); } } App\Status::find(1)->user->email; Retrieve Status Creator Email
  64. Eloquent ORM Normal Usage $statuses = App\Status::all(); foreach ($statuses as

    $status) echo $status->user->email;
  65. Eloquent ORM Normal Usage $statuses = App\Status::all(); foreach ($statuses as

    $status) echo $status->user->email; SELECT * FROM "statuses" foreach result { SELECT * FROM "users" WHERE "id" = 1 } 100 statuses = 101 queries
  66. WTF!? ORMs Suck!

  67. Eloquent ORM $statuses = App\Status::with(‘user’)->get(); foreach ($statuses as $status) echo

    $status->user->email; Eager Loading FTW!
  68. Eloquent ORM $statuses = App\Status::with(‘user’)->get(); foreach ($statuses as $status) echo

    $status->user->email; 100 statuses = 2 queries SELECT * FROM "statuses" SELECT * FROM "users" WHERE "id" IN (1, 2, 3, 4, 5, ...) Eager Loading FTW!
  69. Eloquent ORM creating created updating updated saving saved deleting deleted

    restoring restored Events

  71. Views Route::get('/', function(){ return view('home.index'); //resources/views/home/index.blade.php }); Returning a view

    from a route
  72. Views Route::get('/', function(){ return view(‘home.index') ->with('email', '[email protected]'); Sending data to

    a view
  73. Views Sending data to a view with magic methods Route::get('/',

    function(){ $view = view('home.index'); $view->email = ‘[email protected]’; return $view;
  74. Views Blade Templates Email Address: {{ $email }}

  75. Views Blade Templates Email Address: {{ $email or ‘Please enter

    email’ }}
  76. Views Blade Templates @include(‘user.registration’)

  77. Form Requests

  78. Form Requests Designed just for form handling/validation class CreateStatusRequest extends

    FormRequest { public function rules() { return [ ‘email’ => ‘required|email', ‘text' => ‘required', ]; }
  79. Form Requests class StatusController extends Controller { public function create(CreateStatusRequest

    $request){ … }
  80. Facades

  81. Facades $var = Session::get('foo'); Resolves behind the scenes Getting a

    session variable
  82. Facades Controller Injection to the rescue! Managing Class Responsibilities?

  83. Facades class HomeController extends Controller { public function __construct(Request $request){

    $value = $request->session()->get('key'); } Controller Injection
  84. Drama Da da DOM

  85. That’s a Wrap Utilizes the best PHP has to offer

    Well designed API with great docs Ready to scale architecture Go make cool things and have fun
  86. Community http://github.com/laravel/laravel http://docs.laravel.com http://forums.laravel.com

  87. Resources Dayle Rees - Code Bright Laravel: From Apprentice to

    Artisan LaraCasts
  88. THANKS! Ben Edmunds @benedmunds http://benedmunds.com https://joind.in/16662