Pro Yearly is on sale from $80 to $50! »

Intro to Laravel 5

22f21d5c22b930fd35dd98f25dedf6a4?s=47 Ben Edmunds
September 30, 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.

22f21d5c22b930fd35dd98f25dedf6a4?s=128

Ben Edmunds

September 30, 2016
Tweet

Transcript

  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. Why use it? Full application quick start Authentication Teams Billing

    SASS-y
  20. Let’s do some comparisons

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

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

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

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

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

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

    Views Model / Repository / FLEXIBILITY
  27. Routes

  28. Routes Create routes at: routes/web.php routes/api.php Web = web middleware

    API = api middleware App\Providers\RouteServiceProvider to add new route files
  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 routes/web.php Route::get('/', function(){ echo ‘Boom!’; });

  32. Testing

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

    test
  34. Testing routes/web.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 routes/api.php Route::get(‘user/{id}’, function($id){ return json_encode([ ‘user‘ => User::find($id), ‘success‘

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

    => true ]; });
  41. API App\Providers\RouteServiceProvider protected function mapApiRoutes() { Route::group([ 'middleware' => ['api',

    'auth:api'], 'namespace' => $this->namespace, 'prefix' => 'api', ], function ($router) { require base_path('routes/api.php'); });
  42. API App\Providers\RouteServiceProvider protected function mapApiRoutes() { Route::group([ 'middleware' => ['api',

    'auth:api'], 'namespace' => $this->namespace, 'prefix' => 'api', ], function ($router) { require base_path('routes/api.php'); });
  43. API /tests/api/UserTest.php class UserTest extends TestCase { public function testGetUser()

    { $this->get(‘/api/user/1’) ->seeJson([ ‘success‘ => true ]);
  44. Controllers

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

    I want to use controllers?
  46. Controllers routes/web.php Route::post('status', 'StatusController@create'); class StatusController extends Controller { public

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

  48. Middleware

  49. Middleware Route Filters BETTER FASTER STRONGER Middleware!

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

    Rate Limiting
  51. Middleware Route::post('status', ‘StatusController@create’, [‘middleware’ => ‘auth’] );

  52. Middleware Route::post('status', ‘StatusController@create’, [‘middleware’ => [ ‘first’, ‘second’, ‘third’, ]]

    );
  53. Middleware class AjaxMiddleware implements Middleware { public function handle($request, Closure

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

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

  56. Database Query Builder Eloquent ORM Migrations Seeding

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

    Eloquent ORM
  58. Query Builder $user = DB::table('statuses') ->where(‘email’, 'example@gmail.com’) ->first(); Query Row

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

    => ‘example@gmail.com', 'text' => ‘Vegas Baby! #zendcon’, ]); Insert & Get ID
  60. Eloquent ORM Simple Expressive Efficient

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

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

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

    advanced query
  64. 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
  65. Eloquent ORM Normal Usage $statuses = App\Status::all(); foreach ($statuses as

    $status) echo $status->user->email;
  66. 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
  67. WTF!? ORMs Suck!

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

    $status->user->email; Eager Loading FTW!
  69. 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!
  70. Eloquent ORM creating created updating updated saving saved deleting deleted

    restoring restored Events
  71. Views

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

    from a route
  73. Views Route::get('/', function(){ return view(‘home.index') ->with('email', 'email@gmail.com'); Sending data to

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

    function(){ $view = view('home.index'); $view->email = ‘email@gmail.com’; return $view;
  75. Views Blade Templates Email Address: {{ $email }}

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

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

  78. Echo

  79. Echo Web sockets made easy php artisan make:event MessageReceived /app/Events/MessageReceived.php

  80. Echo Pusher JS or Socket.io

  81. Cashier

  82. Cashier Simple Payment Management Stripe Braintree

  83. Scout

  84. Scout API Authentication JWT OAuth 2 Laravel and Vue JS

  85. Form Requests

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

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

    $request){ … }
  88. Facades

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

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

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

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

  93. 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
  94. Community http://github.com/laravel/laravel http://docs.laravel.com http://forums.laravel.com

  95. Resources Dayle Rees - Code Smart Laravel: From Apprentice to

    Artisan LaraCasts
  96. Securing PHP Apps SecuringPhpApps.com Resources

  97. THANKS! Ben Edmunds @benedmunds http://benedmunds.com https://joind.in/talk/62c46