intro to laravel 4

38
Introduction to Laravel 4 Benson Liang

Upload: singapore-php-user-group

Post on 06-May-2015

3.475 views

Category:

Technology


1 download

DESCRIPTION

Speaker: Liang Anmian Benson http://laravel.com/ Video: http://www.youtube.com/watch?v=gPrdFrivrLo Presented at: Singapore PHP User Group Meetup Oct 2013 Meetup https://www.facebook.com/events/272874456170882/

TRANSCRIPT

Page 1: Intro to Laravel 4

Introduction to Laravel 4Benson Liang

Page 2: Intro to Laravel 4

What will be discussed

Introduction

Installation

The MVC Layers

Authentication

IoC Container

Facade

Service Provider

Page 3: Intro to Laravel 4

Introduction

The Creator

Objectives of Laravel

The Base

Closures

The Syntactic Sugar

Page 4: Intro to Laravel 4

Introduction – The Creator

Taylor Otwell.NET Developer

Page 5: Intro to Laravel 4

Introduction – Objectives of Laravel

Get started on a project FAST

Fun to develop with

Promote S.O.L.I.D design patterns

Singe Responsibility Principle (SRP) Open/Closed Principle (OCP) Liskov Substitution Principle (LSP) Interface Segregation Principle (ISP) Dependency Inversion Principle (DIP)

Page 6: Intro to Laravel 4

Introduction – The Base

Composer friendly

Symfony components

Swiftmailer

Monolog

... and many more

Page 7: Intro to Laravel 4

Introduction - Closures

Introduced in PHP 5.3

Anonymous functions

Useful for specifying callbacks

Route::get( '/login', 'AuthController@showLoginForm');

Route::get('/login', function() { return View::make('auth.loginForm');});

Page 8: Intro to Laravel 4

Introduction – The Syntactic Sugar

Easy to understand

Expressiveness and elegance

Auth::attempt()

Input::get()

Cookie::make()

Event::subscribe()

Page 9: Intro to Laravel 4

Installation

composer create-project laravel/laravel /web/laraveltest --no-dev --prefer-dist

Page 10: Intro to Laravel 4

The MVC Layers

● Eloquent ORM

● Blade Engine

● Controller

Page 11: Intro to Laravel 4

The MVC Layers – Eloquent ORM

● Active record style

● Easy to use

class Book extends Eloquent{ protected $table = 'book'; protected $primaryKey = 'book_id';

public $timestamps = false;}

Page 12: Intro to Laravel 4

The MVC Layers – Eloquent ORM

● Some examples of queries:

● Insert / Update

Book::all();Book::find(1);Book::where('name', '=', 'Michael Cheng');

$b = new Book();$b->title = 'Laravel Basics';$b->description = 'A very nice book';$b->save();

$b = Book::find(2);$b->title = 'Laravel Advanced';$b->save();

Page 13: Intro to Laravel 4

The MVC Layers – Eloquent ORM

● Relationship mapping

public function author(){ return $this->belongsTo('Author', 'author_id');}

Page 14: Intro to Laravel 4

The MVC Layers – Eloquent ORM

● Supports soft delete

protected $softDelete = true;

// Automatically excludes soft deleted rowsBook::all();

// Include soft deleted rowsBook::withTrashed()->get();

// Include only soft deleted rowsBook::onlyTrashed()->get();

// Undo the soft delete$b = Book::withTrashed()->where('book_id, '=', 1);$b->restore();

Page 15: Intro to Laravel 4

The MVC Layers – Eloquent ORM

● Supports query scope

public function scopePopular($query){ return $query->where('rating', '>', '4');}

Book::popular()->get();

Page 16: Intro to Laravel 4

The MVC Layers – Eloquent ORM

● Supports accessors and mutators

// Accessorpublic function getGenderAttribute($value){ return ($value == 'm') ? 'Male' : 'Female';}

// Mutatorpublic function setNameAttribute($value){ $this->attributes['name'] = strtolower($value);}

Page 17: Intro to Laravel 4

The MVC Layers – Blade Engine

● Stock templating engine for Laravel

● Supports template inheritance and sections

<html> <head> <title>@yield('page_title')</title> @yield('css') @yield('javascript') </head>

<body> Some text @yield('content') </body></html>

Page 18: Intro to Laravel 4

The MVC Layers – Blade Engine

@extends('layout')

@section('page_title', 'Login Page')

@section('css') <link rel="stylesheet" type="text/css" href="mystyle.css" />@endsection

@section('javascript') <script type='text/javascript' src='jquery.js'></script>@endsection

@section('content') This is the content for a particular page.@endsection

Page 19: Intro to Laravel 4

The MVC Layers – Blade Engine

● Some control structures

@if (.....) ....

@elseif ....@else ....

@endif

@unless (....) ....@endunless

Page 20: Intro to Laravel 4

The MVC Layers – Blade Engine

@for (....) ....@endfor

@while (....) ....@endwhile

@foreach (....) ....@endforeach

Page 21: Intro to Laravel 4

The MVC Layers – Blade Engine

● Alternate way to echo variable values

My name is <?php echo $user->name ?>

My name is {{ $user->name }}

Page 22: Intro to Laravel 4

The MVC Layers - Controller

● Basic controller

// The controller itselfclass AuthController extends BaseController{ public function showLoginForm() { return View::make('auth.loginForm'); }}

// Routing fileRoute::get('/auth', 'AuthController@showLoginForm')

Page 23: Intro to Laravel 4

The MVC Layers - Controller

● RESTful controller

// The controller itselfclass BookController extends BaseController{ public function getShowAll() { // .............. }

public function postAdd() { // .............. }}

// Routing fileRoute::controller('/books', 'BookController');

Page 24: Intro to Laravel 4

The MVC Layers - Controller

Resource controller

– Generated using Artisan CLI

– Allows easy RESTful implementation

Page 25: Intro to Laravel 4

The MVC Layers - Controller

Resource controller

Paths and route names are generated automatically

Verb Path Action Route Name

GET /resource index resource.index

GET /resource/create create resource.create

POST /resource/ store resource.store

GET /resource/{id} show resource.show

GET /resource/{id}/edit edit resource.edit

PUT / PATCH /resource/{id} update resource.update

DELETE /resource/{id} destroy resource.destroy

Page 26: Intro to Laravel 4

The MVC Layers

● Simple demo

Page 27: Intro to Laravel 4

Authentication

● Allows easy implementation of user authentication for your application

Supports multiple types of authentication

HTTP Basic Application level

Page 28: Intro to Laravel 4

Authentication – Application Level

● Many convenience methods

// Attempt to loginAuth::attempt(array('email' => $email, 'password' => $pwd))

// Check if the current user is logged inAuth::check();

// Access the logged in user$name = Auth::user()->name;

// Manually login a user with its IDAuth::loginUsingId(1);

// Log the user outAuth::logout();

Page 29: Intro to Laravel 4

Authentication – Application Level

Uses Bcrypt as the default hashing algorithm, with a default workload of 8

Workload can be changed freely

Algorithm itself can be changed by framework extension

// Workload 8 by default$hash = Hash::make('password');

// Change workload$hash = Hash::make('password', array('rounds' => 12));

Page 30: Intro to Laravel 4

IoC Container

For managing class dependencies

Promotes inversion of control by injecting dependencies at runtime

Promotes greater flexibility by allowing dependency implementations to be swapped easily

2 ways for resolving types:

Closure Automatic Resolution

Page 31: Intro to Laravel 4

IoC Container

Closure

App::bind('user_manager', function($app){ return new UserRepository();});

// .........// .........// .........// .........

$um = App::make('user_manager');

Page 32: Intro to Laravel 4

IoC Container

Automatic Resolution

class UserManager{ private $repo;

public function __construct(UserRepository $repo) { $this->repo = $repo; }

}

$u = App::make('UserManager');

Page 33: Intro to Laravel 4

IoC Container

Automatic Resolution

class UserManager{ private $repo;

public function __construct(UserRepositoryInterface $repo) { $this->repo = $repo; }

}

// Interface resolutionApp::bind('UserRepositoryInterface', 'DbUserRepository');

// Now we can use the IoC container to resolve the dependencies$u = App::make('UserManager');

Page 34: Intro to Laravel 4

Facade

● Provides a static-like syntax to access objects and their methods in the IoC container

● These are facades in action, and they are NOT static method calls:

Auth::attempt()

Input::get()

Cookie::make()

Event::subscribe()

Page 35: Intro to Laravel 4

Facade

● How does it work?

An object is registered into the IoC container A facade is created to reference that object An alias is defined to use the facade without importing

its namespace

Page 36: Intro to Laravel 4

Service Provider

● A great way to add reusable components into your application

● Custom authentication driver, database driver, support modules etc etc etc...

Page 37: Intro to Laravel 4

Service Provider

class MongoDBServiceProvider extends ServiceProvider{ public function register() { $this->app->bind('mongodb', function() { return new MongoDbManager(); }); }}

// Register the service providerApp::register('MongoDBServiceProvider');

// Now you can use the Mongo DB manager$mongodb = App::make('mongodb');$mongodb->connect(....);$mongodb->add(....);

Page 38: Intro to Laravel 4

Tips For Learning Laravel

● Documentation is your best friend

● Read the API to discover features not mentioned in the documentation

● Get used to closures

● Learn the IoC container and service provider (MUST)