laravel for web artisans

72
LARAVEL PHP FRAMEWORK FOR WEB ARTISANS

Upload: raf-kewl

Post on 06-May-2015

3.307 views

Category:

Software


5 download

DESCRIPTION

Presentation slides on used at the TechTalk of Kickstart Maldives. Introduces Laravel PHP framework.

TRANSCRIPT

Page 1: Laravel for Web Artisans

LARAVELPHP FRAMEWORK FOR WEB ARTISANS

Page 2: Laravel for Web Artisans

Taylor OtwellCreator of Laravel

www.taylorotwell.com

@taylorotwell

http://taylorotwell.com/on-community/

Page 3: Laravel for Web Artisans

http://www.github.com/laravel/laravel

V 4.2.X Current Release

Page 4: Laravel for Web Artisans

Google Trendsfrom 2004 to current

Page 5: Laravel for Web Artisans
Page 6: Laravel for Web Artisans

<? WHY ?>

Page 7: Laravel for Web Artisans

Easy to Learn

Page 8: Laravel for Web Artisans

Ready For Tomorrow

Page 9: Laravel for Web Artisans

Great Community

Page 10: Laravel for Web Artisans

Composer Powered

www.getcomposer.org

Dependency Manager for PHP

Page 11: Laravel for Web Artisans

Eloquent ORM

Page 12: Laravel for Web Artisans

Easy for TDD

FAIL PASS

REFACTOR

Page 13: Laravel for Web Artisans

INSTALLATION

It’s too easy, I don’t have to tell you.

Page 14: Laravel for Web Artisans

IoCInverse of Control

Illuminate\Container\Container

Page 15: Laravel for Web Artisans

Wikipedia

In software engineering, inversion of control describes a design in which

custom-written portions of a computer program receive the flow of control from

a generic, reusable library“what you get when your program make a call”

“Removing dependency from the code”

Page 16: Laravel for Web Artisans

Simplifying Dependency Injection

$object = new SomeClass($dependency1, $dependency2);

$object = App::make(‘SomeClass’);

Page 17: Laravel for Web Artisans

Hard-coded source dependency

public function sendEmail(){

$mailer = new Mailer;$mailer->send();

}

public function sendEmail(){

$mailer = App::make(‘Mailer’);$mailer->send();

}

IoC Resolution

Page 18: Laravel for Web Artisans

Telling IoC what we need

$Bar = App::make(‘Bar’); // new Bar;

App::bind(‘Bar’, ‘MockBar’);

$Bar = App::make(‘Bar’); // new MockBar;

Page 19: Laravel for Web Artisans

Simple ways to bind to the IoC

App::bind(‘SomeClass’, function() { return new Foo;

});

$fooObject = new Foo;$object = App::bind(‘SomeClass’, $fooObject);

App::bind(‘SomeClass’, ‘Foo’);

Page 20: Laravel for Web Artisans

Singleton Dependencies

$object = App::singleton(‘CurrentUser’, function() {

$auth = App::make(‘Auth’);return $auth->user(); // returns user object

});

Page 21: Laravel for Web Artisans

Automatic Dependency Resolution

class EmailService {

public function __construct(Mailer $mailer){

$this->mailer = $mailer;}

public function sendEmail() {$this->mailer->send();

}}

$EmailService = App::make(‘EmailService’);

Page 22: Laravel for Web Artisans

Service Providers

Page 23: Laravel for Web Artisans

Service Providers

use Illuminate\Support\ServiceProvider;

class ContentServiceProvider extends ServiceProvider {

public function register(){

$this->app->bind(‘PostInterface’, ‘\My\Name\Space\Post’);}

}

App::register(‘ContentServiceProvider’); // Registering at Runtime

Page 24: Laravel for Web Artisans

Laravel Facades

Illuminate/Support/Facades/Facade

Page 25: Laravel for Web Artisans

What is FacadeIn Laravel Context

Facade is a class that provide access to an object registered

in the IoC container.

Facade Class

IoC Container

Object A

Facades enable you to hide complex interface behind a simple one.

Page 26: Laravel for Web Artisans

What is happening?

Illuminate/Support/Facades/Route

Route::get(‘/’, ‘HomeController@getIndex’);

$app->make(‘router’)->get(‘/’, ‘HomeController@getIndex’);

Illuminate/Routing/Router

Page 27: Laravel for Web Artisans

Facades in LaravelIlluminate/Support/Facades/

App Artisan Auth Blade Cache Config Cookie Crypt

DB Event File Form Hash HTML Input Lang

Log Mail Paginator Password Queue Redirect Redis

Request Response Route Schema ViewSession SSH URL Validator

Illuminate/Foundation/Application

Page 28: Laravel for Web Artisans

EloquentTalking to your data

Illuminate\Database\Eloquent\Model

Page 29: Laravel for Web Artisans

$result = mysql_query(“SELECT * FROM `users`”);

How you query in plain PHP 5.4 or less (deprecated)

$mysqli = new mysqli(“localhost”, “user”,”password”,”database”);$result = $mysqli->query(“SELECT * FROM `users` “);

How you query in plain PHP 5.5 or above

User::all();

In Laravel 4, does the same query

Page 30: Laravel for Web Artisans

User::all();

DB::table(‘users’)->get();

Illuminate\Database\Query\Builder

What happens when you use Eloquent ORM

Page 31: Laravel for Web Artisans

Create, Read, Update, Delete

Post::create($data);

Post::find($id);

Post::find($id)->update($data);

Post::delete($id);

Page 32: Laravel for Web Artisans

Eloquent Model Class

class Post extends Eloquent {

public function comments() { return $this->hasMany(‘Comment’);

}

public function author() { return $this->belongsTo(‘User’);

}

public function scopePublished($q) { return $q->where(‘publish’,’=‘,1);

} }

Page 33: Laravel for Web Artisans

Eloquent Model Class

class Post extends Eloquent {

public function comments() { return $this->hasMany(‘Comment’);

}

public function author() { return $this->belongsTo(‘User’);

}

public function scopePublished($q) { return $q->where(‘publish’,’=‘,1);

} }

Page 34: Laravel for Web Artisans

$post = Post::find($id);$author = post->author; // get the author object

Get Post’s Author Object

$posts = Post::with(‘author’)->get();

Get Posts including Authors

Page 35: Laravel for Web Artisans

Get Post Comments Approved

$post = Post::find($id);$comments = $post->comments()

->where(‘approved’, true)->get();

Page 36: Laravel for Web Artisans

Model with Query Scope

$published_posts = Post::published()->get(); // gets all posts published

$published_posts = Post::where(‘publish’, ‘=‘, true)->get();// gets all posts published

Page 37: Laravel for Web Artisans

Query Scope Example

class Post extends Eloquent {

public function comments() { return $this->hasMany(‘Comment’);

}

public function author() { return $this->belongsTo(‘User’);

}

public function scopePublished($q) {

return $q->where(‘publish’,’=‘,1);}

}

Page 38: Laravel for Web Artisans

Eloquent Relations

Page 39: Laravel for Web Artisans

Eloquent Relationship One to One(hasOne)

class User

$this->hasOne(‘Profile’, ‘user_id’);

function Profile()

Users

pK: id

username

email

Profile

pk: id

fK: user_id

url

Page 40: Laravel for Web Artisans

class Post

$this-> hasMany(‘Comment’);

function comments()

Posts

pK: id

title

user_id

Comments

pk: id

fK: post_id

user_id

Eloquent Relationship One to Many(hasMany)

Page 41: Laravel for Web Artisans

class User

$this-> belongsToMany(‘Group’)

;

function groups()

Users

pK: id

username

email

Groups

pk: id

Name

Group_User

user_id

group_id

Eloquent Relationship Many to Many

(belongsToMany)

Page 42: Laravel for Web Artisans

class Country

$this-> hasManyThrough(‘User’

);

function posts()

Countries

pK: id

name

code

Posts

pk: id

user_id

title

bodyUsers

pK: id

country_id

username

email

Eloquent Relationship One to Many through(hasManyThrough)

Page 43: Laravel for Web Artisans

Eloquent Relationship Polymorphic Association

$user->image; $movie->image;

class Movie

$this-> morphMany(‘Photo’,

‘imageable);

function image()

Profile

pK: id

user_id

preferencesPhotos

pk: id

file_path

imageable_id

imageable_type

Movie

pK: id

title

released

class Photo

$this-> morphTo();

function imageable()

class Profile

$this-> morphMany(‘Photo’,

‘imageable);

function image()

Page 44: Laravel for Web Artisans

Eloquent Relationship Many to Many Polymorphic Association

$movie->tags; $post->tags;

Posts

pK: id

title

body

Taggables

tag_id

taggable_id

taggable_type

Movie

pK: id

title

released

class Movie

$this-> morphToMany(‘Tag’,

‘Taggable’);

function tags()

Tags

pk: id

name

class Post

$this-> morphToMany(‘Tag’,

‘Taggable’);

function tags()

class Tag

$this-> morphedByMany

(‘Post’, ‘Taggable’);

function posts()$this->

morphedByMany (‘Movie’,

‘Taggable’);

function movies()

Page 45: Laravel for Web Artisans

Underneath Eloquent Model

Query Builder

DB::table(‘users’)->get();

DB::table(‘users’)->where(‘email’, ‘[email protected]’)->first();

DB::table(‘users’)->where(‘votes’, ‘>’, 100)->orWhere(‘votebox’, ‘A’)->get();

Illuminate\Database\Query\Builder

Page 46: Laravel for Web Artisans

Complex Queries via Query Builder

DB::table(‘users’)->join(‘contacts’, function($join) {

$join->on(‘users.id’, ‘=‘, ‘contacts.user_id’)->whereNotNull(‘contacts.mobile_number’);

})->leftJoin(‘submissions’,’users.id’, ‘=‘, ‘submissions.user_id’)->whereExists(function($query) {

$query->select(DB::raw(1))->from(‘reviews’)->whereRaw(‘reviews.user_id = users.id’);

})->whereYear(‘users.joined_date’, ‘>’, 2010)->get();

Get all users joined after year 2010 having over 1000 visits and having submitted reviews. Only select users

with their contacts having mobile numbers and include if they have any content submitted.

Page 47: Laravel for Web Artisans

Find out remaining 70% of Eloquent Features from the

documentation

Page 48: Laravel for Web Artisans

Routing

Wolf

Page 49: Laravel for Web Artisans

Multiple Routing Paradigms

1. route to closures2. route to controller actions3. route to RESTful controllers4. route to resource

Page 50: Laravel for Web Artisans

Routing to Closure

Route::get(‘techtalks’, function() {return “<h1> Welcome </h1>“;

});

Route::post(‘techtalks’, function() {});

Route::put(‘techtalks/{id}’, function($id) { });

Route::delete(‘techtalks/{id}’, function($id) {});

Route::any(‘techtalks’, function() {});

Page 51: Laravel for Web Artisans

Route Groups and Filters

Route::group([‘prefix’=>’settings’, ‘before’=>’auth’], function() { Route::get(‘users’, function() {

// get a post by id });

});

Route::filter(‘auth’, function() { if (Auth::guest()) return Redirect::guest('login');});

Page 52: Laravel for Web Artisans

Subdomain Routing// Registering sub-domain routesRoute::group([‘domain’ =>’{account}.fihaara.com’], function() {

Route::get(‘/’, function($account) {

return “welcome to “ . $account; });});

Page 53: Laravel for Web Artisans

Routing to a Controller Action

class HomePageController extends BaseController {

public function home(){

return “welcome to home page”;}

}

Route::get(‘/‘, ‘HomePageController@home’);

Page 54: Laravel for Web Artisans

class TechTalksController extends Controller {

public function getIndex() {} /talkspublic function getTalkerProfile($id) {} /talks/talker-profile/1public function getTalk($id) {} /talks/talk/1public function postTalk(){} /talks/talkpublic function putTalk(){} /talks/talkpublic function deleteTalk($id){} /talks/talk/1

}

Routing to RESTful Controller

Route::controller(‘talks’, ‘TechTalksController’);

Public method must be prefixed with an HTTP verb

Page 55: Laravel for Web Artisans

class PostsController extends Controller {

public function index() {} // posts GET public function create() {} // posts/create GET public function store() {} // posts POST public function show($id) {} // posts/{id} GET public function edit($id) {} // posts/{id}/edit GET public function update() {} // posts/{id} PUT public function destroy() {} // posts/{id} DELETE…

Routing to Resource Controller

Route::resource(‘posts’, ‘PostsController’);

Page 56: Laravel for Web Artisans

Other Cool Features

Page 57: Laravel for Web Artisans

Authentication

$credentials = [‘username’=> ‘raftalks’, ‘password’ => ‘secret’];

if (Auth::attempt($credentals) === false){

return Redirect::to(‘login-error’);}

if (Auth::check() === false){

return Redirect::to(‘login’);}

Check if user is authenticated

Page 58: Laravel for Web Artisans

Localization

App::setLocale(‘dv’); echo Lang::get(‘news.world_news’); // out puts “ ުރ� ަބ� ަޚ� ެގ� ޭޔ� ިނ ”ުދ�echo Trans(‘news.world_news’);

Basic Usage

return array(“world_news” =>“ ުރ� ަބ� ަޚ� ެގ� ޭޔ� ިނ ,”ުދ�“news” => “ ުރ� ަބ� ,”ަޚ�…

Lang FileFILE PATH:/app

/lang/dv

news.php

Page 59: Laravel for Web Artisans

Artisan CLI

Laravel ProvidesArtisan Commands for

Rapid Development

You can develop customArtisan commandsfor a package or

an application

Page 60: Laravel for Web Artisans

Creating DB Migration

php artisan migrate:make create_users_table --create=users

class Create_Users_table extends Migration {

public function up() {

Schema::create(‘users’, function(Blueprint $table) {$table->increments(‘id’);$table->string(‘username’, 50);$table->string(‘password’, 200);

});},

public function down() {Schema::drop(‘users’);

}}

Page 61: Laravel for Web Artisans

Seeding into your DB

class DefaultAdminUserSeeder extends Seeder {

public function run() {

DB::table(‘users’)->delete(); // truncates the table data

User::create([‘username’=>’admin’,‘password’=> Hash::make(‘password’)

]);}

}

Page 62: Laravel for Web Artisans

Events

Event::fire(‘news.created’, $post);

Event::listen(‘news.created’,function($post) {

UserPostCounter::increment(‘posts’, $post->user_id);});

Page 63: Laravel for Web Artisans

Mail

Mail::send(‘emails.welcome’, $data, function($message) use($user){

$message->to($user->email, $user->name)->subject(‘Welcome’);

});

uses SwiftMailer Libraryor use API drivers forMailgun or Mandrill

Page 64: Laravel for Web Artisans

QueuesBeanstalkd

Amazon SQSIronMQRedis

Synchronous (for lcoal use)

Queue::push('SendEmail', [‘message' => $message]);

php artisan queue:listen

Page 65: Laravel for Web Artisans

Remote SSH

SSH::run([‘cd /var/www’,‘git pull origin master’

]);

Page 66: Laravel for Web Artisans

Laravel HomesteadUsing Vagrant, we now have easy way to simply manage virtual machines.

Included Softwares• Ubuntu 14.04• PHP 5.5• Nginx• MySQL• Postgres• Node (with Bower, Grunt, Gulp)• Redis• Memcached• Beanstalkd• Laravel Envoy• Fabric + HipChat Extension

Page 67: Laravel for Web Artisans

Sign Up -> Add Your Cloud’s API Key -> Serve Happiness

forge.laravel.com

Page 68: Laravel for Web Artisans

Meet the community @ IRC

Channel: #laravelServer: irc.freenode.netPort: 6667

Page 69: Laravel for Web Artisans

Next Laracon

laracon.eu/2014

Page 70: Laravel for Web Artisans

Laravel Maldives Group

Wouldn’t it be awesome for us to have our own Laracons

Feel free to get in touch with me if you are interested.My Emails: [email protected] / [email protected]

Page 71: Laravel for Web Artisans

???

Page 72: Laravel for Web Artisans

Sleep Well :)