why laravel?

36
1 WHY LARAVEL? “The PHP Framework For Web Artisans” Introduction to Laravel Jonathan Goode

Upload: jonathan-goode

Post on 12-Jan-2017

187 views

Category:

Software


2 download

TRANSCRIPT

Page 1: Why Laravel?

1

WHY LARAVEL?“The PHP Framework For Web Artisans”

Introduction to LaravelJonathan Goode

Page 2: Why Laravel?

2 . 1

HISTORY BEHIND THE VISION, a .NET developer in Arkansas (USA), was using an

early version of CodeIgniter when the idea for Laravel came tohim.“I couldn't add all the features I wanted to”, he says, “withoutmangling the internal code of the framework”.He wanted something leaner, simpler, and more flexible.

Taylor Otwell

Page 3: Why Laravel?

2 . 2

HISTORY BEHIND THE VISIONThose desires, coupled with Taylor's .NET background, spawnedthe framework that would become Laravel.He used the ideas of the .NET infrastructure which Microso hadbuilt and spent hundreds of millions of dollars of research on.With Laravel, Taylor sought to create a framework that would beknown for its simplicity.

He added to that simplicity by including an expressive syntax, clear structure,and incredibly thorough documentation.

With that, Laravel was born.

Page 4: Why Laravel?

3 . 1

THE EVOLUTION OF LARAVELTaylor started with a simple routing layer and a really simplecontroller-type interface (MVC)

v1 and v2 were released in June 2011 and September 2011 respectively, justmonths apart

In February 2012, Laravel 3 was released just over a year laterand this is when Laravel's user base and popularity really beganto grow.

Page 5: Why Laravel?

3 . 2

THE EVOLUTION OF LARAVELIn May 2013, Laravel 4 was released as a complete rewrite of theframework and incorporated a package manager called

.Composer is an application-level package manager for PHP thatallowed people to collaborate instead of compete.Before Composer, there was no way to take two separatepackages and use different pieces of those packages together tocreate a single solution.Laravel is built on top of several packages most notably

.

Composer

Symfony

Page 6: Why Laravel?

3 . 3

LARAVEL TODAYLaravel now stands at version 5.3 with 5.4 currently indevelopmentSupport for PHP 7 has recently been added to Laravel 4.2.20and for the first version ever, long term support has beenguaranteed for 5.1

Page 7: Why Laravel?

4 . 1

ARCHITECTUREModel

Everything database related - Eloquent ORM (Object RelationalMapper)

ViewHTML structure - Blade templating engine

ControllerProcessing requests and generating output

+ Facades, Dependency Injection, Repositories, etc...

Page 8: Why Laravel?

4 . 2

FIRSTLY, WHY OBJECT ORIENTED PHP?Logic is split into classes where each class has specific attributesand behaviours.This leads to code that is more maintainable, more predictableand simpler to test.

Page 9: Why Laravel?

5 . 1

ROUTESRoutes (/routes) hold the applicationURLs

web.php for web routesapi.php for stateless requestsconsole.php for Artisan commands

// Visiting '/' will return 'Hello World!' Route::get('/', function() return 'Hello World!'; );

Page 10: Why Laravel?

5 . 2

Route::get('/tasks/id', 'TasksController@view');

Visiting /tasks/3 will call the controller method that dealswith viewing that task that has an id of 3

Page 11: Why Laravel?

5 . 2

5 . 3

Route::post('/tasks/add', 'TasksController@store');

Handles posting for data when creating a formNo need to check forisset($_POST['input'])

Page 12: Why Laravel?

5 . 3

6 . 1

CONTROLLERSHandle the logic required for processing requests

namespace App\Http\Controllers\Admin;

class TasksController extends Controller public function view($id) return "This is task " . $id;

Page 13: Why Laravel?

6 . 2

ENHANCED CONTROLLER

namespace App\Http\Controllers\Admin;

class TasksController extends Controller public function view($id) // Finds the task with 'id' = $id in the tasks table $task = Task::find($id);

// Returns a view with the task data return View::make('tasks.view')­>with(compact('task'));

Page 14: Why Laravel?

7 . 1

MODELSClasses that are used to access thedatabase

A Task model would be tied to the tasks table in MySQL

namespace App\Models;

use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes;

class Task extends Model use SoftDeletes;

protected $fillable = ['title', 'done',]; protected $dates = ['deleted_at'];

Page 15: Why Laravel?

7 . 2

QUERIES

// Retrieves the tasks that have a high priority Task::where('priority', '=', 'high')­>get(); Task::wherePriority('high')­>get(); // *Magic*!

// Retrieves all the tasks in the database Task::all();

// Retrieves a paginated view for tasks, 20 tasks per page Task::paginate(20);

// Inserts a new task into the database Task::create(['description' => 'Buy milk']);

// (Soft) deletes the task with an id of 5 Task::find(5)­>delete();

// Permanently deletes all soft deleted tasks Task::onlyTrashed()­>forceDelete();

Page 16: Why Laravel?

8 . 1

VIEWSBlade is a simple, yet powerful templating engine provided withLaravel

// This view uses the master layout @extends('layouts.master')

@section('content') <p>This is my body content.</p> @stop

@section('sidebar') <p>This is appended to the master sidebar.</p> @stop

Page 17: Why Laravel?

8 . 28 . 3

@foreach($tasks as $task) <p> $task­>title </p> @endforeach

=

<?php foreach ($tasks as $task) <p><?php echo $task­>title ?></p> <?php endforeach ?>

Page 18: Why Laravel?

8 . 3

8 . 4

<p>Tasks:</p> <table> <thead> <tr> <th>ID</th> <th>Title</th> </tr> </thead> <tbody> @foreach($tasks as $task) <tr> <td> $task­>id </td> <td> $task­>title </td> </tr> @endforeach </tbody> </table>

Page 19: Why Laravel?

8 . 4

9 . 1

ARTISANArtisan is the command-line interface included with LaravelIt provides a number of helpful commands that can assist youwhile you build your application

$ php artisan list

$ php artisan help migrate

Page 20: Why Laravel?

9 . 2

DATA MIGRATION AND SEEDING

$ php artisan make:migration create_users_table Migration created successfully!

$ php artisan migrate ­­seed Migrated: 2016_01_12_000000_create_users_table Migrated: 2016_01_12_100000_create_password_resets_table Migrated: 2016_01_13_162500_create_projects_table Migrated: 2016_01_13_162508_create_servers_table

Page 21: Why Laravel?

10 . 1

KEY CHANGES IN LARAVEL 5DIRECTORY STRUCTURE

Laravel 5 implements the autoloading standard whichmeans all your classes are namespacedThe default namespace for your web application is app

You can change this using php artisan app:name <your‐app‐name>

assets, views, and lang now live in a resources folderconfig, storage, database, and tests directories havebeen moved to the root of the projectbootstrap, public, and vendor retain their place

PSR-4

Page 22: Why Laravel?

10 . 2

KEY CHANGES IN LARAVEL 5ENVIRONMENT DETECTION

Instead of all the complex nested configuration directories, youhave a .env file at the root of your project to take careof the application environment and all the environmentvariables.It is useful to create a .env.example file to provide a templatefor other team members to follow

(dotEnv)

Page 23: Why Laravel?

10 . 3

KEY CHANGES IN LARAVEL 5ROUTE MIDDLEWARE

Middleware can be used to add extra layers to your HTTP routes.If you want code to execute before every route or before specificroutes in your application, then such a piece of code is a good fitfor a middleware class.For example, let's say you want to block out a certain range ofIPs from your application to make your application unavailablein that region.In such a case, you will need to check the client IP before everyrequest and allow/disallow them entry to your application.

$ php artisan make:middleware "RegionMiddleware"

Page 24: Why Laravel?

10 . 4

KEY CHANGES IN LARAVEL 5METHOD INJECTION

Until version 4.2, you had to request the Inversion of Control(IoC) container to provide a class instance or create it in yourcontroller's constructor to make it accessible under the classscope.Now, you can declare the type hinted class instance in thecontroller method's signature and the IoC container will takecare of it, even if there are multiple parameters in your controllerfunction's signature.

Page 25: Why Laravel?

10 . 5

EXAMPLE OF METHOD INJECTION

// TaskController.php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller; use App\Http\Requests\Admin\TaskUpdateRequest; use App\Models\Task;

class TaskController extends Controller public function store(TaskUpdateRequest $request) $task = Task::create($request­>except('_token')); return redirect(route('admin.task.index'))­>with('success', trans('general.created', ['what' => 'Task']));

/**/

class TaskUpdateRequest extends FormRequest public function rules() return ['title' => 'required|min:3|unique:tasks,title',];

Page 26: Why Laravel?

10 . 6

KEY CHANGES IN LARAVEL 5CONTRACTS

Contracts are actually interface classes in disguise.Interfaces are a tried and tested method for removing classdependency and developing loosely coupled so warecomponents.

.Most of the major core components make use of these contracts to keep theframework loosely coupled.

Laravel buys into the same philosophy

Page 27: Why Laravel?

10 . 7

KEY CHANGES IN LARAVEL 5AUTHENTICATION

Authentication is part of almost all the web applications youdevelop, and a lot of time is spent writing the authenticationboilerplate.This is not the case any more with Laravel 5. The databasemigrations, models, controllers, and views just need to beconfigured to make it all work.Laravel 5 has a Registrar service, which is a crucial part of thisout of the box, ready to use authentication system.

Page 28: Why Laravel?

10 . 8

OTHER KEY CHANGES IN LARAVEL 5Queue and TaskScheduling

Crons taken care of

Multiple File SystemsLocal or remote (cloud based)

Route CachingEventsCommands

Page 29: Why Laravel?

11 . 1

LARAVEL ELIXIR provides a fluent, expressive interface to compiling

and concatenating your assets.If you've ever been intimidated by learning Gulp or Grunt, fearno more.Elixir makes it a cinch to get started using Gulp to compile Sassand other assets.It can even be configured to run your tests

Laravel Elixir

(Assumes sass is located at resources/assets/sass , etc.)

Page 30: Why Laravel?

11 . 2

// gulpfile.js

const elixir = require('laravel­elixir'); elixir.config.publicPath = 'public_html/assets';

require('laravel­elixir­vue­2');

elixir(mix => mix.sass('app.scss') .webpack('app.js') .copy('node_modules/bootstrap­sass/assets/fonts/bootstrap/', 'public_html/assets/fonts/bootstrap'); );

Page 31: Why Laravel?

11 . 2

11 . 3

// Run all tasks and build your assets $ gulp

// Run all tasks and minify all CSS and JavaScript $ gulp ­­production

// Watch your assets for any changes ­ re­build when required $ gulp watch

Page 32: Why Laravel?

11 . 3

12

LARAVEL STARTER Created specifically to speed up development at UofAImproved version of Laravel 4.1 with backportedenhancements from 4.2

This was due to the version of PHP (5.3.8) we previously had to use

Has code specific for the way we have to work with webaccounts

Configured to use public_html rather than publicLDAP integration complete with configuration for abdn.ac.ukEnhanced String and Array helpersUofA logosetc.

Currently in the process of updating for Laravel 5.3

Page 33: Why Laravel?

13 . 1

LARAVEL HAS MORE UP ITS SLEEVESTANDALONE SERVICES

Provision and deploy unlimited PHP applications on DigitalOcean, Linode,and AWS

A package that provides scaffolding for subscription billing, invoices, etc.

A deployment service focused on the deployment side of applications andincludes things like zero downtime deploys, health checks, cron jobmonitoring, and more

Forge

Spark

Envoyer

Page 34: Why Laravel?

13 . 2

LARAVEL HAS MORE UP ITS SLEEVEBAKED INTO LARAVEL 5

Event broadcasting, evolved. Bring the power of WebSockets to yourapplication without the complexity.

API authentication without the headache. Passport is an OAuth2 server that'sready in minutes.

Driver based full-text search for Eloquent, complete with pagination andautomatic indexing.

Laravel Echo

Laravel Passport

Laravel Scout

Page 35: Why Laravel?

13 . 3

LARAVEL HAS MORE UP ITS SLEEVEOTHER DEVELOPMENT TOOLS

Powered by Vagrant, Homestead gets your entire team on the same pagewith the latest PHP, MySQL, Postgres, Redis, and more.

Cachet is the best way to inform customers of downtime. This is your statuspage.

If all you need is an API and lightning fast speed, try Lumen. It's Laravelsmaller-light.

Need a CMS that runs on Laravel and is built for developers and clients? Lookno further.

Homestead

Cachet

Lumen

Statamic

Page 36: Why Laravel?

14

MORE RESOURCES

Over 900 videos covering all aspects of usingLaravel

https://laravel.com/https://laracasts.com/