SlideShare una empresa de Scribd logo
1 de 72
LARAVEL
PHP FRAMEWORK FOR WEB ARTISANS
Taylor Otwell
Creator of Laravel
www.taylorotwell.com
@taylorotwell
http://taylorotwell.com/on-community/
http://www.github.com/laravel/laravel
V 4.2.X Current Release
Google Trends
from 2004 to current
<? WHY ?>
Easy to Learn
Ready For Tomorrow
Great Community
Composer Powered
www.getcomposer.org
Dependency Manager for PHP
Eloquent ORM
Easy for TDD
FAIL PASS
REFACTOR
INSTALLATION
It’s too easy, I don’t have to tell you.
IoC
Inverse of Control
IlluminateContainerContainer
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 IlluminateSupportServiceProvider;
class ContentServiceProvider extends ServiceProvider {
public function register()
{
$this->app->bind(‘PostInterface’, ‘MyNameSpacePost’);
}
}
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
Class
IoC Container Object A
cades 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 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 ViewSession SSH URL Validator
Illuminate/Foundation/Application
Eloquent
Talking to your data
IlluminateDatabaseEloquentModel
$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();
IlluminateDatabaseQueryBuilder
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
email
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
email
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
body
Users
pK: id
country_id
username
email
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
preferences
Photos
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’, ‘raftalks@gmail.com’)->first();
DB::table(‘users’)->where(‘votes’, ‘>’, 100)
->orWhere(‘votebox’, ‘A’)->get();
IlluminateDatabaseQueryBuilder
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 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’);
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
}
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 File
FILE PATH:
/app
/lang
/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: 7909000@gmail.com / raftalks@gmail.com
???
Sleep Well :)

Más contenido relacionado

La actualidad más candente

Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In DepthKirk Bushell
 
Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.SWAAM Tech
 
Laravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingLaravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingChristopher Pecoraro
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Viral Solani
 
10 Laravel packages everyone should know
10 Laravel packages everyone should know10 Laravel packages everyone should know
10 Laravel packages everyone should knowPovilas Korop
 
Laravel.IO A Use-Case Architecture
Laravel.IO A Use-Case ArchitectureLaravel.IO A Use-Case Architecture
Laravel.IO A Use-Case ArchitectureShawn McCool
 
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin Lorvent56
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel frameworkAhmad Fatoni
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroChristopher Pecoraro
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design PatternsBobby Bouwmann
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Laravel Restful API and AngularJS
Laravel Restful API and AngularJSLaravel Restful API and AngularJS
Laravel Restful API and AngularJSBlake Newman
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5Soheil Khodayari
 
Knowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkKnowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkBukhori Aqid
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravelConfiz
 

La actualidad más candente (20)

Why Laravel?
Why Laravel?Why Laravel?
Why Laravel?
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
 
Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.
 
Laravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingLaravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routing
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
 
10 Laravel packages everyone should know
10 Laravel packages everyone should know10 Laravel packages everyone should know
10 Laravel packages everyone should know
 
Intro to Laravel
Intro to LaravelIntro to Laravel
Intro to Laravel
 
Laravel.IO A Use-Case Architecture
Laravel.IO A Use-Case ArchitectureLaravel.IO A Use-Case Architecture
Laravel.IO A Use-Case Architecture
 
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Presentation laravel 5 4
Presentation laravel 5 4Presentation laravel 5 4
Presentation laravel 5 4
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
 
Javascript laravel's friend
Javascript laravel's friendJavascript laravel's friend
Javascript laravel's friend
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Laravel Restful API and AngularJS
Laravel Restful API and AngularJSLaravel Restful API and AngularJS
Laravel Restful API and AngularJS
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5
 
Knowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkKnowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP framework
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravel
 

Destacado

Laravel and Composer
Laravel and ComposerLaravel and Composer
Laravel and ComposerPhil Sturgeon
 
Hire laravel-php-developers- Hire Laravel Programmers
Hire laravel-php-developers- Hire Laravel ProgrammersHire laravel-php-developers- Hire Laravel Programmers
Hire laravel-php-developers- Hire Laravel ProgrammersSummation IT
 
Database Relationships
Database RelationshipsDatabase Relationships
Database Relationshipswmassie
 
Internet of Things
Internet of ThingsInternet of Things
Internet of ThingsNisha Patel
 
Intro to Laravel PHP Framework
Intro to Laravel PHP FrameworkIntro to Laravel PHP Framework
Intro to Laravel PHP FrameworkBill Condo
 
Konfigurasi Dasar Windows Server 2012 R2 rev.1
Konfigurasi Dasar Windows Server 2012 R2 rev.1Konfigurasi Dasar Windows Server 2012 R2 rev.1
Konfigurasi Dasar Windows Server 2012 R2 rev.1Muhamad Yusuf Supriadi
 

Destacado (11)

Laravel and Composer
Laravel and ComposerLaravel and Composer
Laravel and Composer
 
Laravel Meetup
Laravel MeetupLaravel Meetup
Laravel Meetup
 
Hire laravel-php-developers- Hire Laravel Programmers
Hire laravel-php-developers- Hire Laravel ProgrammersHire laravel-php-developers- Hire Laravel Programmers
Hire laravel-php-developers- Hire Laravel Programmers
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Database Relationships
Database RelationshipsDatabase Relationships
Database Relationships
 
Laravel Introduction
Laravel IntroductionLaravel Introduction
Laravel Introduction
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Intro to Laravel PHP Framework
Intro to Laravel PHP FrameworkIntro to Laravel PHP Framework
Intro to Laravel PHP Framework
 
Konfigurasi Dasar Windows Server 2012 R2 rev.1
Konfigurasi Dasar Windows Server 2012 R2 rev.1Konfigurasi Dasar Windows Server 2012 R2 rev.1
Konfigurasi Dasar Windows Server 2012 R2 rev.1
 
Laravel 5.4
Laravel 5.4 Laravel 5.4
Laravel 5.4
 
SlideShare 101
SlideShare 101SlideShare 101
SlideShare 101
 

Similar a Laravel PHP Framework Guide

Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravelwajrcs
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Hugo Hamon
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 

Similar a Laravel PHP Framework Guide (20)

Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravel
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Zendcon 09
Zendcon 09Zendcon 09
Zendcon 09
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Fatc
FatcFatc
Fatc
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Phinx talk
Phinx talkPhinx talk
Phinx talk
 
Hexagonal architecture in PHP
Hexagonal architecture in PHPHexagonal architecture in PHP
Hexagonal architecture in PHP
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Php summary
Php summaryPhp summary
Php summary
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Symfony2 revealed
Symfony2 revealedSymfony2 revealed
Symfony2 revealed
 

Último

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 

Último (20)

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 

Laravel PHP Framework Guide

  • 2. Taylor Otwell Creator of Laravel www.taylorotwell.com @taylorotwell http://taylorotwell.com/on-community/
  • 5.
  • 12. Easy for TDD FAIL PASS REFACTOR
  • 13. INSTALLATION It’s too easy, I don’t have to tell you.
  • 15. 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”
  • 16. Simplifying Dependency Injection $object = new SomeClass($dependency1, $dependency2); $object = App::make(‘SomeClass’);
  • 17. Hard-coded source dependency public function sendEmail() { $mailer = new Mailer; $mailer->send(); } public function sendEmail() { $mailer = App::make(‘Mailer’); $mailer->send(); } IoC Resolution
  • 18. Telling IoC what we need $Bar = App::make(‘Bar’); // new Bar; App::bind(‘Bar’, ‘MockBar’); $Bar = App::make(‘Bar’); // new MockBar;
  • 19. 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’);
  • 20. Singleton Dependencies $object = App::singleton(‘CurrentUser’, function() { $auth = App::make(‘Auth’); return $auth->user(); // returns user object });
  • 21. Automatic Dependency Resolution class EmailService { public function __construct(Mailer $mailer) { $this->mailer = $mailer; } public function sendEmail() { $this->mailer->send(); } } $EmailService = App::make(‘EmailService’);
  • 23. Service Providers use IlluminateSupportServiceProvider; class ContentServiceProvider extends ServiceProvider { public function register() { $this->app->bind(‘PostInterface’, ‘MyNameSpacePost’); } } App::register(‘ContentServiceProvider’); // Registering at Runtime
  • 25. What is Facade In Laravel Context Facade is a class that provide access to an object registered in the IoC container. Facade Class IoC Container Object A cades enable you to hide complex interface behind a simple one.
  • 26. What is happening? Illuminate/Support/Facades/Route Route::get(‘/’, ‘HomeController@getIndex’); $app->make(‘router’)->get(‘/’, ‘HomeController@getIndex’); Illuminate/Routing/Router
  • 27. 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 ViewSession SSH URL Validator Illuminate/Foundation/Application
  • 28. Eloquent Talking to your data IlluminateDatabaseEloquentModel
  • 29. $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
  • 31. Create, Read, Update, Delete Post::create($data); Post::find($id); Post::find($id)->update($data); Post::delete($id);
  • 32. 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); } }
  • 33. 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); } }
  • 34. $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
  • 35. Get Post Comments Approved $post = Post::find($id); $comments = $post->comments() ->where(‘approved’, true)->get();
  • 36. Model with Query Scope $published_posts = Post::published()->get(); // gets all posts published $published_posts = Post::where(‘publish’, ‘=‘, true)->get(); // gets all posts published
  • 37. 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); } }
  • 39. 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
  • 40. 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)
  • 41. 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)
  • 42. class Country $this-> hasManyThrough(‘User’); function posts() Countries pK: id name code Posts pk: id user_id title body Users pK: id country_id username email Eloquent Relationship One to Many through (hasManyThrough)
  • 43. Eloquent Relationship Polymorphic Association $user->image; $movie->image; class Movie $this-> morphMany(‘Photo’, ‘imageable); function image() Profile pK: id user_id preferences Photos 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()
  • 44. 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()
  • 45. Underneath Eloquent Model Query Builder DB::table(‘users’)->get(); DB::table(‘users’)->where(‘email’, ‘raftalks@gmail.com’)->first(); DB::table(‘users’)->where(‘votes’, ‘>’, 100) ->orWhere(‘votebox’, ‘A’)->get(); IlluminateDatabaseQueryBuilder
  • 46. 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.
  • 47. Find out remaining 70% of Eloquent Features from the documentation
  • 49. Multiple Routing Paradigms 1. route to closures 2. route to controller actions 3. route to RESTful controllers 4. route to resource
  • 50. 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() { });
  • 51. 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'); });
  • 52. Subdomain Routing // Registering sub-domain routes Route::group([‘domain’ =>’{account}.fihaara.com’], function() { Route::get(‘/’, function($account) { return “welcome to “ . $account; }); });
  • 53. Routing to a Controller Action class HomePageController extends BaseController { public function home() { return “welcome to home page”; } } Route::get(‘/‘, ‘HomePageController@home’);
  • 54. 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 } Routing to RESTful Controller Route::controller(‘talks’, ‘TechTalksController’); Public method must be prefixed with an HTTP verb
  • 55. 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’);
  • 57. 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
  • 58. 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 File FILE PATH: /app /lang /dv news.php
  • 59. Artisan CLI Laravel Provides Artisan Commands for Rapid Development You can develop custom Artisan commands for a package or an application
  • 60. 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’); } }
  • 61. 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’) ]); } }
  • 63. 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
  • 64. Queues Beanstalkd Amazon SQS IronMQ Redis Synchronous (for lcoal use) Queue::push('SendEmail', [‘message' => $message]); php artisan queue:listen
  • 66. 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
  • 67. Sign Up -> Add Your Cloud’s API Key -> Serve Happiness forge.laravel.com
  • 68. Meet the community @ IRC Channel: #laravel Server: irc.freenode.net Port: 6667
  • 70. 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: 7909000@gmail.com / raftalks@gmail.com
  • 71. ???

Notas del editor

  1. Asalaam Alaikum. My name is Rahmathullah. I work for a company called Hummingbird Travel which is not only a travel company, we are working towards a vision, to lead as a travel technology provider. We are using Laravel in our servers.
  2. As you know, I am here to talk about Laravel. I wonder how many of you are using it today. In this talk, I’ll try my best to cover the most important parts of the framework and its features. So lets get started.
  3. Taylor Otwell, the creator of Laravel framework, has done an amazing job. PHP community started inspiring his framework at the very beginning. There are many community websites and companies that promotes Laravel. It is interesting to know, several books on Laravel gets published every year and they are among the best sellers. Laravel have remarkably gained so much popularity among developers in such a short time since it’s first release in 2011.
  4. This is taken from Google Trends. Do you see that blue line. Isn’t this amazing that we know for sure, Laravel is trendy in google. See the short time frame it took to reach almost to the very top when compared against other frameworks. There is one more from Github too.
  5. Laravel is at the top as number one PHP project for this month, even for this week. I think it has been number one for some time now.
  6. Why Laravel ?
  7. Laravel make the coding look clean and beautiful. Documentation is always up to date and maintained so well that it covers almost everything that you need to know about the framework.
  8. You can use Laravel to build huge enterprise applications, or just simple APIs. It utilises the full potential of PHP, making it the most feature rich framework that continues to gain new features and more improvements every day, in other words it is always ready for tomorrow.
  9. Laravel application is powered with composer. Composer is so far the best PHP tool for package management and autoloading. It give us the opportunity to extend the application with different packages from the community. If you don’t know about composer, its time that you start learning about it.
  10. Laravel ships with the amazing Eloquent ORM. Works great on MySQL, PostgreSQL, SQL Server, and SQLite. It’s amazing, as if you would write simple form of instructions to deal with your data and their relationships.
  11. This is just a high level overview of the Request Lifecycle sequence. Lets see a simple animation that will give us a better idea.
  12. There is this bootstrap layer. Whenever a request hits the Index.php the it will start with bootstrapping. It instantiates the Application object and the request gets injected to the Application. It then detects the environment. Loads all the configurations to that environment. Register all the Service Providers Then it will start the application by executing the run method. The run method will go through the internal processes of finding the matching route and then process a response. Application generates a response in the end.
  13. I am not going to talk about the process of installing Laravel framework or how to get started, as there are many simple tutorials that you can find online, not only that, the documentation will show you 3 different ways to install Laravel. so, I will start with IoC.
  14. This is vital information to better understand the framework. Some of you may already know what it means. Inverse of Control is more like the spinal-code of an application. You plug into it all your components, so that they all can work together.
  15. Here is the definition from wikipedia. In short, I can say it’s all about what you get when your program call for something it needs. I can also say it’s all about removing dependency from the code. Lets see an example.
  16. Normally you would instantiate an object as shown above and dependencies will be hardcoded. Laravel provides App class which is the application IoC container, and we can retrieve an instance of an object, without having to hardcode the dependencies.
  17. Lets see this example. The one on top has the hard coded dependency. It’s not testable as we can’t mock that Mailer instance, as we are not passing it in. In the one below, we are resolving the Mailer class instance through the App class. This way whenever we need to mock the Mailer class for unit test, we can tell the IoC to bind a mock instead of returning the real class instance.
  18. Laravel IoC allows us to define what it should be returning when we want a specific class instance. The arrow is pointing to the line where I am registering the class Bar name to a different class using the bind method of the IoC container. This is useful when you need to pass in a mock class for unit testing. There’re different ways to register your classes with IoC container. Lets see them.
  19. These are the basic ways to register a class with the application IoC container. We use the bind method to register a class name and the actual class or instance that it should return.
  20. Laravel’s IoC can handle Automatic Dependency Injection. We can type hint the actual class or interface of the dependency needed to a class in its constructor method. When Laravel’s IoC returns an instance of the class, it will try to figure out the dependencies using PHP’s Reflection class for whatever it is bound to. It will then inject the dependencies automatically.
  21. Laravel provides you the option of creating Service providers. Many of the framework packages are registered to the IoC container using Service Providers.
  22. ServiceProvider can be used to group all your IoC container bindings. A service provider can even register event listeners, view composers, Artisan commands, and so much more.
  23. Now that you all have some basic understanding of Laravel’s IoC, next I am going to tell you about the Facades provided by Laravel.
  24. Before that, lets see what is a facade in Laravel context. A facade class provides static interface to the classes registered in the application IoC container. Facades enable you to hide complex interface behind a simple one.
  25. So, what is actually happening here? For example, the Route is a Facade class that resolves to Router class. When you call a static method through a Facade class, it actually calls that method on the object that gets resolved through the IoC container. You can also get an instance of the class registered in the application IoC without using a facade class.
  26. These are the Facades provided by Laravel, they can be used to access the actual service layers provided by the framework through IoC container. I won’t have the time to explain each one of them, however I will try to touch with some of the cool stuffs later at this talk. Next, my favourite part.
  27. When it comes to deal with data, this is the best ORM I have ever seen. Lets see what Eloquent can do. I will just go through some examples.
  28. If you are hardcoding your database queries into your code, imagine the case when mysql_query extension has deprecated. You will have to refactor each and every file that deals with that function. That’s a disaster. Its difficult to maintain. Its better to use an ORM than hardcoding your database queries. I can say, among those ORMs I have tried, Laravel provides the best. Lets see how it works.
  29. After having your database configuration set for your application, you can simply start making the data model classes that represents your database tables. Then you can use such a class to call simple query methods available through Eloquent. As you can see, I am using the User class model and I am calling all method. When that happens, inside Eloquent, it actually translates the query to the Database Query Builder. (hit [space bar]) Then, this query builder is able to make connection to which ever the database configured as default and it interacts with the database. If you needed support for additional database, you will only need to write a driver to handle through the query builder. So now imagine, when an extension gets deprecated, the only thing that needs to get updated is the connecting database drivers. You won’t need to touch your application codes.
  30. I love Eloquent because it’s so simple, and I think that’s one of the reasons why Laravel is so popular. See, It’s so easy to understand when you code your Database interaction using Eloquent. I don’t even have to explain this slide. Lets take a look at this Post Model class used in this example
  31. Here in this class, I have defined two relationships. Eloquent provides straight forward methods to define the relationships. As you can see the Post has Many Comments. Post belongs to Author. Lets see how some examples for these two relationships.
  32. I can get the author object from the post item object, as in the example on top. I can even get all the posts items including their authors, and this is called eager loading in Laravel.
  33. Here, I have changed the first example slightly different from the previous slide. I am fetching the post comments by adding the query logic to get only comments approved.
  34. In this example, I am eager loading the comments along with a query logic to fetch only those that are approved while fetching all the post items.
  35. Eloquent model can have query scope methods, which is useful to store your common query logics. In the first example, I am fetching Post items having the published status as true. I am writing my query logic there. Instead of writing the query logic, the second example here, I am calling to a query scope method.
  36. Here is the Post class, see the query scope method defined here. A query scope method must be prefixed with “scope” and that method will receive the query builder object to add the logics.
  37. Lets have a look at the types of relationships we can define for an Eloquent model.
  38. One to One, as I may not need to explain what this relation means. In this example, a user have one profile and in the User model class, we can define simply stating that User has One Profile.
  39. Next, One to Many, which is a very common type of relation we deal almost in all the applications. This Post class hasMany Comments.
  40. next, Many to Many and I do use this a lot too, sometimes to maintain a master list that other tables can relate to. See the relationship is defined as the User belongs to many groups.
  41. This is interesting one. This was added from Laravel 4.1 onwards. The idea of this relationship is to get a distant related object through another object. So Country has Many Posts through User.
  42. Polymorphic Association was introduced from Laravel version 4 and I was really happy to see this available. Here in this example, Movies and User Profiles have their own image, and all their images are stored or fetched from the same Photos table.
  43. Eloquent Models do have events that gets triggered while before and after create, update and delete actions. We can register a callback that would get processed when the event gets triggered. In the example here, a callback function to validates the post item is registered with the event handler to run before the post item gets created.
  44. Next, I just want to show some more of the query builder stuffs that we can use. As mentioned earlier, this is exactly the same thing that goes underneath the Eloquent ORM. We can query our data without using a Model. We can straight away use Query builder using the Facade class called DB. These are some basic examples of db queries regardless of which type of database we are using.
  45. Here is a complex query using the Query Builder. [ Read the slide text ] Now imagine how you would have to write this query to all the different types of databases that you want to support. Thanks to Laravel’s awesome database query builder which handles any complex situations. Trust me, I have done much more complex queries than this which deals with transactions and data ranges.
  46. I just covered most of the new and rich features of the Eloquent Model and Query Builder. Lets jump to next topic.
  47. Alright, here I am at the Routes now. “Where should I go ?” I assume most of you would know what it means by routing. In simple words, routing gives direction to your application logic. It is also responsible in returning a response in the end. it’s basically about what needs to be processed based on a given URL.
  48. Laravel offers multiple routing options. You can route to a closure. You can route to a controller action, as this is how most MVC frameworks are designed. You can route to a Restful controller, where the actions are determined by http verb that it should be responding. You can route to Resource which is similar to Rails where you route to a resource.
  49. The simplest way to put your routes in Laravel is routing directly to a closure. In this example, you can see the Route registered directly to a closure and it can be set to respond to a http request method, like get, post, put, delete or any of them using any.
  50. Route Group is really cool because you can put bunch of routes to it and define the options that gets affected to all of them. In this example, I have set the option to prefix all the routes URI and applied auth filter before any route gets processed. Down below, shows how the auth filter is registered using Route filter method. So in this case, if the user is not logged in, the user will get redirected to the login url.
  51. Subdomain routing is very cool. If you like to create something like a SaaS, where you put up accounts as the subdomains. A basic example would be to run an online shop manager service. Where store owners would use the application to access their shop using their account as the subdomain.
  52. Some complex ones. The first one, shows a constraint defined with regular expression to only accept numeric value for the URL parameter. Next, grouping routes to a sub domain. So all the routes defined in this group will be able to take the subdomain as a parameter. See the route inside the group, which is enforcing over secured HTTP request only.
  53. Here is a basic example on routing to a controller action. In this type of controllers, you are free to bind your routes directly to a specific method of your controller.
  54. Here is a Restful Controller. A Restful controller uses simple REST naming conventions, as you can see in this example, they are prefixed to the controller method names.
  55. A Resource Controller is interesting. Similar to the RESTful Controller, the resource controllers makes it easier to build RESTful controllers around the resources.
  56. A Route should be able to return a response. To achieve this Laravel provides two useful Facades. Response and Views. Lets start with Response.
  57. From a route we can return a string or an array. If its an array, by default it gives a JSON response. We can even define a custom Response using the Response class. Here in this example I am using the Response class to render a view file with data injected.
  58. Response is handy when we want to do a lot more while giving a response. In this example, a cookie gets attached with the response. We can even set the http response headers to a response object.
  59. View is a type of response. A View is expected to return HTML and it handles rendering HTML views with data passed to it.
  60. Laravel offers easy ways to bind data to the views. There are so much to talk about views too. Views can be nested with sub views. Laravel offers out of the box templating engine called Blade, which is another area to cover about view layouts etc. All of these features are so simple to learn but however I do not have the time to explain them all. I will show few examples.
  61. View Composer. This is interesting, as it is similar to decorator pattern where you can modify a specific view before it gets rendered. In this example, I am setting the header title with the name of the blog and the post title.
  62. Here is just a small preview of a basic Blade template. I won’t be able to explain them all. So keep in mind there is an awesome Templating engine called Blade which will help you do layouts for your application easily. Please do check it out from the documentation.
  63. Lets see the other cool stuffs in Laravel.
  64. Laravel is shipped with out of the box Authentication service. You can easily authenticate users and check if users are authenticated. You can even extend this class to make it work for you any way you like.
  65. Laravel supports localisation, so if you plan to support your web application or web site with multiple languages, Laravel provides an easy way to do it.
  66. This is one of my favorite tool. Laravel provides its own command line tool to run many of the tasks it provides for rapid development. There are generators for generating controllers, database migration files, or even you can add your own custom commands. Through Artisan you can even run the PHP server, without much configurations, you can straight away see your application from the browser.
  67. Laravel provides easy way to write your database schema using the Schema class. Usually this is used with a migration class, so that we can generate the database tables easily without using a database administrating tool. The Migration classes can be used for version controlling of your database.
  68. Seeding is a way to populate your database tables with your default data, such as master lists like list of countries, posts categories, or default user account. Seeding will be useful at application installation as well as when unit testing with test data.
  69. If you are big fan of event driven development, Laravel offers that too. Some of the components like the Eloquent, Authentication class do trigger events that you can actually bind actions to it. You can even fire your own custom events and have listeners perform the necessary actions whenever that event gets triggered.
  70. Sending an email from your application to a user or someone, shouldn’t be too hard to do it with Laravel. Laravel offers simple Mail facade thats can utlize the swift mailer library by default or we can configure it to work with other APIs using drivers.
  71. Yeah I know, I can’t stop this from here. There are still more stuffs that you should know.
  72. If you like to improve your application by handing over the time consuming tasks such as sending an email using a queue system, that runs the tasks outside the scope of your application, you won’t find any thing as easy as what you get with Laravel Queues. It’s pretty awesome. It supports most of the popular queues like IronMQ and Amazon SQS. You can even have your own que runner like Beanstalkd on your own server.
  73. This is super cool. Now that via SSH, we can make apps that can talk to each other remotely or even make an application that can remotely manage servers or deployment of your projects. So much is there that you can do with the power of SSH.
  74. When version 4.2 beta was announced at the Laracon 2014 in NewYork, 2 weeks ago, Taylor introduced this nice cool feature called Laravel Homestead. It’s actually a Vagrant box configured specifically for Laravel. Using vagrant, you can replicate your production server in your development machine, no more pain in getting errors when you switch to your production sever. I would recommend this to all of you.
  75. To get your self into the Laravel community, the best place to get community support is through Laravel channel on IRC free node.
  76. If you are like me, get ready for the next Laracon in Amsterdam, join the journey to meet the people we see talking about Laravel. Share and gain more knowledge. It’s worth visiting a Laracon event.
  77. I am taking this opportunity to let you guys know that we could try having the Asia’s first Laracon event here in Maldives. So I am interested to form a group, and I do welcome everyone to be part of it. Feel free to contact me. Thank you.