0% found this document useful (0 votes)
87 views

Laravel For Web Artisans

This document provides an overview of Laravel, a PHP web framework. It discusses key Laravel concepts like IoC/Dependency Injection, Facades, Eloquent ORM, and relationships. Laravel uses IoC to resolve dependencies and make objects available via the container. Facades provide simple access to underlying framework classes. Eloquent is an ORM that allows interacting with databases using object-oriented syntax like Model::all(). Relationships define connections between models.

Uploaded by

indofree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

Laravel For Web Artisans

This document provides an overview of Laravel, a PHP web framework. It discusses key Laravel concepts like IoC/Dependency Injection, Facades, Eloquent ORM, and relationships. Laravel uses IoC to resolve dependencies and make objects available via the container. Facades provide simple access to underlying framework classes. Eloquent is an ORM that allows interacting with databases using object-oriented syntax like Model::all(). Relationships define connections between models.

Uploaded by

indofree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

LARAVEL

PHP FRAMEWORK FOR WEB ARTISANS


Taylor Otwell
Creator of Laravel

www.taylorotwell.com
@taylorotwell

http://taylorotwell.com/on-community/
V 4.2.X Current Release

http://www.github.com/laravel/laravel
Google Trends
from 2004 to current
<? WHY ?>
Easy to Learn
Ready For Tomorrow
Great Community
Composer Powered

Dependency Manager for PHP


www.getcomposer.org
Eloquent ORM
Easy for TDD

FAIL PASS

REFACTOR
INSTALLATION
It’s too easy, I don’t have to tell you.
IoC
Inverse of Control

Illuminate\Container\Container
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”


Wikipedia
Simplifying Dependency Injection

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

$object = App::make(‘SomeClass’);
Hard-coded source dependency
public function sendEmail()
{
$mailer = new Mailer;
$mailer->send();
}

IoC Resolution
public function sendEmail()
{
$mailer = App::make(‘Mailer’);
$mailer->send();
}
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’, ‘Foo’);

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

$fooObject = new Foo;


$object = App::bind(‘SomeClass’, $fooObject);
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 Facade
In Laravel Context

Facade is a class that provide access


to an object registered
in the IoC container.

Facade
IoC Container Object A
Class

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


What is happening?

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

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

Illuminate/Support/Facades/Route Illuminate/Routing/Router
Facades in Laravel
Illuminate/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 Session SSH URL Validator View

Illuminate/Foundation/Application
Eloquent
Talking to your data

Illuminate\Database\Eloquent\Model
How you query in plain PHP 5.4 or less (deprecated)

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

How you query in plain PHP 5.5 or above

$mysqli = new mysqli(“localhost”, “user”,”password”,”database”);


$result = $mysqli->query(“SELECT * FROM `users` “);

In Laravel 4, does the same query

User::all();
What happens when you use Eloquent ORM

User::all();

Illuminate\Database\Query\Builder

DB::table(‘users’)->get();
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);
}
}
Get Post’s Author Object

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

Get Posts including Authors

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

$post = Post::find($id);
$comments = $post->comments()
->where(‘approved’, true)->get();
Model with Query Scope

$published_posts = Post::where(‘publish’, ‘=‘, true)->get();


// gets all posts published

$published_posts = Post::published()->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)

Users Profile
pK: id pk: id
username fK: user_id
email url

class User

function Profile()
$this->hasOne(‘Profile’,
‘user_id’);
Eloquent Relationship
One to Many
(hasMany)

Posts Comments
pK: id pk: id
title fK: post_id
user_id user_id

class Post

function comments()
$this->
hasMany(‘Comment’);
Eloquent Relationship
Many to Many
(belongsToMany)
Users Groups
pK: id pk: id
username Name
email
Group_User

user_id

group_id

class User

function groups()
$this->
belongsToMany(‘Group’);
Eloquent Relationship
One to Many through
(hasManyThrough)
Countries Posts
pK: id pk: id
name user_id
code title
Users
body
pK: id
country_id
username
email

class Country

function posts()
$this->
hasManyThrough(‘User’);
Eloquent Relationship
Polymorphic Association
Profile
pK: id
user_id Photos
Movie preferences pk: id
pK: id file_path
title imageable_id
released imageable_type

class Profile class Movie class Photo

function image() function image() function imageable()


$this-> morphMany(‘Photo’, $this-> morphMany(‘Photo’,
$this-> morphTo();
‘imageable); ‘imageable);

$user->image; $movie->image;
Eloquent Relationship
Many to Many Polymorphic Association
Posts
pK: id
title Taggables Tags
Movie body tag_id pk: id
pK: id taggable_id name
title
taggable_type
released

class Movie class Post class Tag


function tags() function tags() function posts() function movies()
$this-> $this-> $this-> $this->
morphToMany(‘Tag’, morphToMany(‘Tag’, morphedByMany morphedByMany
‘Taggable’); ‘Taggable’); (‘Post’, ‘Taggable’); (‘Movie’, ‘Taggable’);

$movie->tags; $post->tags;
Underneath Eloquent Model
Query Builder
Illuminate\Database\Query\Builder

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

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

DB::table(‘users’)->where(‘votes’, ‘>’, 100)


->orWhere(‘votebox’, ‘A’)->get();
Complex Queries via Query Builder
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.

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();
Find out remaining 70% of Eloquent
Features from the documentation
Routing

Wolf
Multiple Routing Paradigms

1. route to closures
2. route to controller actions
3. route to RESTful controllers
4. 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 routes
Route::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’);
Routing to RESTful Controller
class TechTalksController extends Controller {

public function getIndex() {} /talks


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

Public method must be prefixed with an HTTP verb

Route::controller(‘talks’, ‘TechTalksController’);
Routing to Resource Controller
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

Route::resource(‘posts’, ‘PostsController’);
Other Cool Features
Authentication
$credentials = [‘username’=> ‘raftalks’, ‘password’ => ‘secret’];

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


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

Check if user is authenticated

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


{
return Redirect::to(‘login’);
}
Localization
Basic Usage
App::setLocale(‘dv’);
echo Lang::get(‘news.world_news’); // out puts “‫ނުދ‬ ޭ ‫ބަޚ ެގ‬
ި ‫ޔ‬ ަ ‫ރ‬
ު ”
echo Trans(‘news.world_news’);

Lang File
FILE PATH:
/app
return array(
“world_news” => “‫ނުދ‬ ޭ ‫ބަޚ ެގ‬
ި ‫ޔ‬ ަ ‫ރ‬
ު ”, /lang
“news” => “‫ބަޚ‬
ަ ‫ރ‬
ު ”, /dv
… news.php
Artisan CLI
Laravel Provides
Artisan Commands for
Rapid Development

You can develop custom


Artisan commands
for 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
Mail::send(‘emails.welcome’, $data, function($message) use($user)
{
$message->to($user->email, $user->name)
->subject(‘Welcome’);
});

uses SwiftMailer Library


or use API drivers for
Mailgun or Mandrill
Queues
Beanstalkd
Amazon SQS
IronMQ
Redis
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 Homestead
ng Vagrant, we now have easy way to simply manage virtual mac

Included Softwares
• Ubuntu 14.04
• PHP 5.5
• Nginx
• MySQL
• Postgres
• Node (with Bower, Grunt, Gulp)
• Redis
• Memcached
• Beanstalkd
• Laravel Envoy
• Fabric + HipChat Extension
Sign Up -> Add Your Cloud’s API Key -> Serve Happiness

forge.laravel.com
Meet the community @
IRC

Channel: #laravel
Server: irc.freenode.net
Port: 6667
Next Laracon

laracon.eu/2014
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 :)

You might also like