Download - Laravel for Web Artisans
LARAVELPHP FRAMEWORK FOR WEB ARTISANS
Taylor OtwellCreator of Laravel
www.taylorotwell.com
@taylorotwell
http://taylorotwell.com/on-community/
Google Trendsfrom 2004 to current
<? WHY ?>
Easy to Learn
Ready For Tomorrow
Great Community
Eloquent ORM
Easy for TDD
FAIL PASS
REFACTOR
INSTALLATION
It’s too easy, I don’t have to tell you.
IoCInverse of Control
Illuminate\Container\Container
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”
Simplifying Dependency Injection
$object = new SomeClass($dependency1, $dependency2);
$object = App::make(‘SomeClass’);
Hard-coded source dependency
public function sendEmail(){
$mailer = new Mailer;$mailer->send();
}
public function sendEmail(){
$mailer = App::make(‘Mailer’);$mailer->send();
}
IoC Resolution
Telling IoC what we need
$Bar = App::make(‘Bar’); // new Bar;
App::bind(‘Bar’, ‘MockBar’);
$Bar = App::make(‘Bar’); // new MockBar;
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’);
Singleton Dependencies
$object = App::singleton(‘CurrentUser’, function() {
$auth = App::make(‘Auth’);return $auth->user(); // returns user object
});
Automatic Dependency Resolution
class EmailService {
public function __construct(Mailer $mailer){
$this->mailer = $mailer;}
public function sendEmail() {$this->mailer->send();
}}
$EmailService = App::make(‘EmailService’);
Service Providers
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
Laravel Facades
Illuminate/Support/Facades/Facade
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.
What is happening?
Illuminate/Support/Facades/Route
Route::get(‘/’, ‘HomeController@getIndex’);
$app->make(‘router’)->get(‘/’, ‘HomeController@getIndex’);
Illuminate/Routing/Router
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
EloquentTalking to your data
Illuminate\Database\Eloquent\Model
$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
User::all();
DB::table(‘users’)->get();
Illuminate\Database\Query\Builder
What happens when you use Eloquent ORM
Create, Read, Update, Delete
Post::create($data);
Post::find($id);
Post::find($id)->update($data);
Post::delete($id);
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);
} }
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);
} }
$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
Get Post Comments Approved
$post = Post::find($id);$comments = $post->comments()
->where(‘approved’, true)->get();
Model with Query Scope
$published_posts = Post::published()->get(); // gets all posts published
$published_posts = Post::where(‘publish’, ‘=‘, true)->get();// gets all posts published
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);}
}
Eloquent Relations
Eloquent Relationship One to One(hasOne)
class User
$this->hasOne(‘Profile’, ‘user_id’);
function Profile()
Users
pK: id
username
Profile
pk: id
fK: user_id
url
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)
class User
$this-> belongsToMany(‘Group’)
;
function groups()
Users
pK: id
username
Groups
pk: id
Name
Group_User
user_id
group_id
Eloquent Relationship Many to Many
(belongsToMany)
class Country
$this-> hasManyThrough(‘User’
);
function posts()
Countries
pK: id
name
code
Posts
pk: id
user_id
title
bodyUsers
pK: id
country_id
username
Eloquent Relationship One to Many through(hasManyThrough)
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()
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()
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
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.
Find out remaining 70% of Eloquent Features from the
documentation
Routing
Wolf
Multiple Routing Paradigms
1. route to closures2. route to controller actions3. route to RESTful controllers4. route to resource
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() {});
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');});
Subdomain Routing// Registering sub-domain routesRoute::group([‘domain’ =>’{account}.fihaara.com’], function() {
Route::get(‘/’, function($account) {
return “welcome to “ . $account; });});
Routing to a Controller Action
class HomePageController extends BaseController {
public function home(){
return “welcome to home page”;}
}
Route::get(‘/‘, ‘HomePageController@home’);
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
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’);
Other Cool Features
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
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
Artisan CLI
Laravel ProvidesArtisan Commands for
Rapid Development
You can develop customArtisan commandsfor a package or
an application
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’);
}}
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’)
]);}
}
Events
Event::fire(‘news.created’, $post);
Event::listen(‘news.created’,function($post) {
UserPostCounter::increment(‘posts’, $post->user_id);});
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
QueuesBeanstalkd
Amazon SQSIronMQRedis
Synchronous (for lcoal use)
Queue::push('SendEmail', [‘message' => $message]);
php artisan queue:listen
Remote SSH
SSH::run([‘cd /var/www’,‘git pull origin master’
]);
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
Meet the community @ IRC
Channel: #laravelServer: irc.freenode.netPort: 6667
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]
???
Sleep Well :)