SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
Building Scalable
applications with Laravel
Laravel - PHP Framework For Web Artisans
Lumen
The stunningly fast micro-framework by Laravel.
Lumen is the perfect solution for
building Laravel based
micro-services and blazing fast APIs
Laravel ● Middleware
● Dependency Injection
● Filesystem / Cloud Storage
● Queues
● Task Scheduling
● Database
○ Query Builder
○ Migrations
○ Seeding
● LUCID Architecture
Middleware
HTTP middleware provide a convenient mechanism for filtering
HTTP requests entering your application.
● Maintenance
● Authentication
● CSRF protection
MeetingMogul
Validate twilio requests (Header Signature)
<?php
namespace AppHttpMiddleware;
use Log;
use Closure;
use AppRepositoriesTwilioAccountTwilioAccountRepositoryInterface;
class ValidateTwilioRequestMiddleware
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!$this->validateRequest($request)) {
throw new SymfonyComponentHttpKernelExceptionUnauthorizedHttpException('Twilio', 'You are not authorized to access this
resource.');
}
return $next($request);
}
}
Dependency Injection
Laravel provides a convenient way to inject dependencies
seemlessly.
<?php
namespace Database;
class Database
{
protected $adapter;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
}
<?php
namespace AppApiv1Controllers;
use AppApiTransformersMessageStatusTransformer;
use AppRepositoriesUserUserRepositoryInterface;
/**
* Message Resource
*
* @Resource("Message", uri="/messages")
*/
class MessageController extends BaseController
{
protected $userRepo;
public function __construct(Request $request, UserRepositoryInterface $userRepo)
{
parent::__construct($request);
$this->userRepo = $userRepo;
}
protected function setMessagingStatus(Request $request)
{
$this->userRepo->createOrUpdateProfile($this->auth->user(), $request->all());
return (['message' => 'Message Status updated successfully.']);
}
}
<?php
namespace AppRepositories;
use IlluminateSupportServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* @var array
*/
protected $bindings = [
UserUserRepositoryInterface::class => UserUserRepository::class,
BuddyBuddyRepositoryInterface::class => BuddyBuddyRepository::class,
ProfileProfileRepositoryInterface::class => ProfileProfileRepository::class,
ContentContentRepositoryInterface::class => ContentContentRepository::class,
];
/**
* @return void
*/
public function register()
{
foreach ($this->bindings as $interface => $implementation) {
$this->app->bind($interface, $implementation);
}
}
}
Cloud Storage
Laravel provides a powerful filesystem abstraction. It
provides simple to use drivers for working with Local
filesystems, Amazon S3 and Rackspace Cloud Storage. Even
better, it's amazingly simple to switch between these
storage options as the API remains the same for each system.
Cloud Storage
public function updateAvatar(Request $request, $id)
{
$user = User::findOrFail($id);
Storage::put(
'avatars/'.$user->id,
file_get_contents($request->file('avatar')->getRealPath())
);
}
Queues
The Laravel queue service provides a unified API across a
variety of different queue back-ends.
$job = (new SendReminderEmail($user))->onQueue('emails');
$this->dispatch($job);
Available Queue Drivers:
Database, Beanstalkd, Amazon SQS, Redis, and synchronous
(for local use) driver
Task Scheduling
The Laravel command scheduler allows you to fluently and
expressively define your command schedule within Laravel
itself, and only a single Cron entry is needed on your
server.
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
DB::table('recent_users')->delete();
})->daily();
$schedule->command('emails:send')->weekly()->mondays()->at('13:00');
$schedule->command('emails:send')->withoutOverlapping();
}
Database
Query Builder
Migrations
Seeding
Elequent ORM
Query Builder
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
Migrations
Migrations are like version control for your database.
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
});
Seeding
Laravel includes a simple method of seeding your database
with test data using seed classes.
<?php
use IlluminateDatabaseSeeder;
use IlluminateDatabaseEloquentModel;
class DatabaseSeeder extends Seeder
{
public function run()
{
DB::table('users')->insert([
'name' => str_random(10),
'email' => str_random(10).'@gmail.com',
'password' => bcrypt('secret'),
]);
}
}
Eloquent ORM
● Convention over configuration
● Timestamps automatically managed (Carbon)
● Soft Deleting
● Query Scopes
Eloquent ORM - Soft Delete
● Active Record implementation
php artisan make:model User --migration
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
class Flight extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
}
LUCID
Architecture
An Architecture is a pattern of
connected Structures.
LUCID architecture Designed at vinelab
to get rid of rotting/legacy code.
Architecture
Controller View
Model
Service/
Domain
Communicate Structures
● No more legacy code
● Defines Terminology
● Comprehensive, No limitations
● Complements Laravel’s Design
● Balance performance and design
Lucid Components
Feature
Job
Service
Lucid * Feature
● As described in business, as a class name
● Runs Jobs - Steps in the process of accomplishment
CreateArticleFeature
LoginUserFeature
Controller Feature
Serves
Controller serves Feature
Lucid * Job
A class that does one thing; responsible for the business logic
● Validate Article Input
● Generate Slug
● Upload Files To CDN
● Save Article
● Respond With Json
CreateArticleFeature
Lucid * Job
A class that does one thing; responsible for the business logic
● ValidateArticleInputJob
● GenerateSlugJob
● UploadFilesToCDNJob
● SaveArticleJob
● RespondWithJsonJob
CreateArticleFeature
Lucid * Job
A class that does one thing; responsible for the business logic
Lucid * Service
Implements Features and serves them through controllers
● Website
● Api
● Backend
Lucid * Domains
Responsible for the entities; exposing their
functionalities through Jobs
Lucid * Domains
● Article
○ GetPublishedArticlesJob
○ SaveArticleJob
○ ValidateArticleInputJob
● CDN
○ UploadFilesToCdnJob
● HTTP
○ RespondWithJsonJob
Lucid * Principles
● Controllers serve Features
● Avoid Cross-Domain Communication
● Avoid Cross-Job Communication
Best Practices
● Standards (PHP-FIG)
○ Autoloading
○ Code Style
● Interfaces
● Components
○ Carbon
○ Intervention
● Pull Requests &
● Code Reviews on GitHub
Question & Answer

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)
Dave Haeffner
 
Semi Automatic Code Review
Semi Automatic Code ReviewSemi Automatic Code Review
Semi Automatic Code Review
Richard Huang
 

Was ist angesagt? (20)

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
 
Laravel and CodeIgniter: pros & cons
Laravel and CodeIgniter: pros & consLaravel and CodeIgniter: pros & cons
Laravel and CodeIgniter: pros & cons
 
Laravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web ArtisansLaravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web Artisans
 
Laravel
LaravelLaravel
Laravel
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5
 
Laravel overview
Laravel overviewLaravel overview
Laravel overview
 
Android Continuous Integration and Automation - Enrique Lopez Manas, Sixt
Android Continuous Integration and Automation - Enrique Lopez Manas, SixtAndroid Continuous Integration and Automation - Enrique Lopez Manas, Sixt
Android Continuous Integration and Automation - Enrique Lopez Manas, Sixt
 
Zen and the Art of REST API documentation - MuCon London 2015
Zen and the Art of REST API documentation - MuCon London 2015Zen and the Art of REST API documentation - MuCon London 2015
Zen and the Art of REST API documentation - MuCon London 2015
 
Web presentation
Web presentationWeb presentation
Web presentation
 
Testing Alfresco extensions
Testing Alfresco extensionsTesting Alfresco extensions
Testing Alfresco extensions
 
Console Apps: php artisan forthe:win
Console Apps: php artisan forthe:win Console Apps: php artisan forthe:win
Console Apps: php artisan forthe:win
 
Laravelの良いところ
Laravelの良いところLaravelの良いところ
Laravelの良いところ
 
Sbt, idea and eclipse
Sbt, idea and eclipseSbt, idea and eclipse
Sbt, idea and eclipse
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Releasing High Quality Packages - Longhorn PHP 2021
Releasing High Quality Packages - Longhorn PHP 2021Releasing High Quality Packages - Longhorn PHP 2021
Releasing High Quality Packages - Longhorn PHP 2021
 
Postman
PostmanPostman
Postman
 
How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)
 
Functional Reactive Programming
Functional Reactive ProgrammingFunctional Reactive Programming
Functional Reactive Programming
 
20171108 PDN HOL React Basics
20171108 PDN HOL React Basics20171108 PDN HOL React Basics
20171108 PDN HOL React Basics
 
Semi Automatic Code Review
Semi Automatic Code ReviewSemi Automatic Code Review
Semi Automatic Code Review
 

Ähnlich wie Building Scalable Applications with Laravel

Using Apache as an Application Server
Using Apache as an Application ServerUsing Apache as an Application Server
Using Apache as an Application Server
Phil Windley
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 

Ähnlich wie Building Scalable Applications with Laravel (20)

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...
 
Using Apache as an Application Server
Using Apache as an Application ServerUsing Apache as an Application Server
Using Apache as an Application Server
 
Why Laravel?
Why Laravel?Why Laravel?
Why Laravel?
 
laravel-interview-questions.pdf
laravel-interview-questions.pdflaravel-interview-questions.pdf
laravel-interview-questions.pdf
 
Memphis php 01 22-13 - laravel basics
Memphis php 01 22-13 - laravel basicsMemphis php 01 22-13 - laravel basics
Memphis php 01 22-13 - laravel basics
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Serverless APIs with JavaScript - Matt Searle - ChocPanda
Serverless APIs with JavaScript - Matt Searle - ChocPandaServerless APIs with JavaScript - Matt Searle - ChocPanda
Serverless APIs with JavaScript - Matt Searle - ChocPanda
 
Extending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsExtending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on Rails
 
Laravel Meetup
Laravel MeetupLaravel Meetup
Laravel Meetup
 
Grails 101
Grails 101Grails 101
Grails 101
 
Decompose the monolith into AWS Step Functions
Decompose the monolith into AWS Step FunctionsDecompose the monolith into AWS Step Functions
Decompose the monolith into AWS Step Functions
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with java
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Ruby on Rails All Hands Meeting
Ruby on Rails All Hands MeetingRuby on Rails All Hands Meeting
Ruby on Rails All Hands Meeting
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
 
Knolx session
Knolx sessionKnolx session
Knolx session
 
Laravel & Composer presentation - extended
Laravel & Composer presentation - extendedLaravel & Composer presentation - extended
Laravel & Composer presentation - extended
 
Serverless cat detector workshop - cloudyna 2017 (16.12.2017)
Serverless cat detector   workshop - cloudyna 2017 (16.12.2017)Serverless cat detector   workshop - cloudyna 2017 (16.12.2017)
Serverless cat detector workshop - cloudyna 2017 (16.12.2017)
 

Kürzlich hochgeladen

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Kürzlich hochgeladen (20)

WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 

Building Scalable Applications with Laravel

  • 1. Building Scalable applications with Laravel Laravel - PHP Framework For Web Artisans
  • 2. Lumen The stunningly fast micro-framework by Laravel. Lumen is the perfect solution for building Laravel based micro-services and blazing fast APIs
  • 3. Laravel ● Middleware ● Dependency Injection ● Filesystem / Cloud Storage ● Queues ● Task Scheduling ● Database ○ Query Builder ○ Migrations ○ Seeding ● LUCID Architecture
  • 4. Middleware HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. ● Maintenance ● Authentication ● CSRF protection MeetingMogul Validate twilio requests (Header Signature)
  • 5. <?php namespace AppHttpMiddleware; use Log; use Closure; use AppRepositoriesTwilioAccountTwilioAccountRepositoryInterface; class ValidateTwilioRequestMiddleware { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!$this->validateRequest($request)) { throw new SymfonyComponentHttpKernelExceptionUnauthorizedHttpException('Twilio', 'You are not authorized to access this resource.'); } return $next($request); } }
  • 6. Dependency Injection Laravel provides a convenient way to inject dependencies seemlessly. <?php namespace Database; class Database { protected $adapter; public function __construct(AdapterInterface $adapter) { $this->adapter = $adapter; } }
  • 7. <?php namespace AppApiv1Controllers; use AppApiTransformersMessageStatusTransformer; use AppRepositoriesUserUserRepositoryInterface; /** * Message Resource * * @Resource("Message", uri="/messages") */ class MessageController extends BaseController { protected $userRepo; public function __construct(Request $request, UserRepositoryInterface $userRepo) { parent::__construct($request); $this->userRepo = $userRepo; } protected function setMessagingStatus(Request $request) { $this->userRepo->createOrUpdateProfile($this->auth->user(), $request->all()); return (['message' => 'Message Status updated successfully.']); } }
  • 8. <?php namespace AppRepositories; use IlluminateSupportServiceProvider; class RepositoryServiceProvider extends ServiceProvider { /** * @var array */ protected $bindings = [ UserUserRepositoryInterface::class => UserUserRepository::class, BuddyBuddyRepositoryInterface::class => BuddyBuddyRepository::class, ProfileProfileRepositoryInterface::class => ProfileProfileRepository::class, ContentContentRepositoryInterface::class => ContentContentRepository::class, ]; /** * @return void */ public function register() { foreach ($this->bindings as $interface => $implementation) { $this->app->bind($interface, $implementation); } } }
  • 9. Cloud Storage Laravel provides a powerful filesystem abstraction. It provides simple to use drivers for working with Local filesystems, Amazon S3 and Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system.
  • 10. Cloud Storage public function updateAvatar(Request $request, $id) { $user = User::findOrFail($id); Storage::put( 'avatars/'.$user->id, file_get_contents($request->file('avatar')->getRealPath()) ); }
  • 11. Queues The Laravel queue service provides a unified API across a variety of different queue back-ends. $job = (new SendReminderEmail($user))->onQueue('emails'); $this->dispatch($job); Available Queue Drivers: Database, Beanstalkd, Amazon SQS, Redis, and synchronous (for local use) driver
  • 12. Task Scheduling The Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server. protected function schedule(Schedule $schedule) { $schedule->call(function () { DB::table('recent_users')->delete(); })->daily(); $schedule->command('emails:send')->weekly()->mondays()->at('13:00'); $schedule->command('emails:send')->withoutOverlapping(); }
  • 14. Query Builder DB::transaction(function () { DB::table('users')->update(['votes' => 1]); DB::table('posts')->delete(); });
  • 15. Migrations Migrations are like version control for your database. Schema::create('users', function (Blueprint $table) { $table->increments('id'); });
  • 16. Seeding Laravel includes a simple method of seeding your database with test data using seed classes. <?php use IlluminateDatabaseSeeder; use IlluminateDatabaseEloquentModel; class DatabaseSeeder extends Seeder { public function run() { DB::table('users')->insert([ 'name' => str_random(10), 'email' => str_random(10).'@gmail.com', 'password' => bcrypt('secret'), ]); } }
  • 17. Eloquent ORM ● Convention over configuration ● Timestamps automatically managed (Carbon) ● Soft Deleting ● Query Scopes
  • 18. Eloquent ORM - Soft Delete ● Active Record implementation php artisan make:model User --migration <?php namespace App; use IlluminateDatabaseEloquentModel; use IlluminateDatabaseEloquentSoftDeletes; class Flight extends Model { use SoftDeletes; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = ['deleted_at']; }
  • 19. LUCID Architecture An Architecture is a pattern of connected Structures. LUCID architecture Designed at vinelab to get rid of rotting/legacy code.
  • 22. ● No more legacy code ● Defines Terminology ● Comprehensive, No limitations ● Complements Laravel’s Design ● Balance performance and design
  • 24. Lucid * Feature ● As described in business, as a class name ● Runs Jobs - Steps in the process of accomplishment CreateArticleFeature LoginUserFeature Controller Feature Serves
  • 26.
  • 27.
  • 28.
  • 29.
  • 30. Lucid * Job A class that does one thing; responsible for the business logic ● Validate Article Input ● Generate Slug ● Upload Files To CDN ● Save Article ● Respond With Json CreateArticleFeature
  • 31. Lucid * Job A class that does one thing; responsible for the business logic ● ValidateArticleInputJob ● GenerateSlugJob ● UploadFilesToCDNJob ● SaveArticleJob ● RespondWithJsonJob CreateArticleFeature
  • 32. Lucid * Job A class that does one thing; responsible for the business logic
  • 33.
  • 34.
  • 35.
  • 36.
  • 37. Lucid * Service Implements Features and serves them through controllers ● Website ● Api ● Backend
  • 38.
  • 39.
  • 40. Lucid * Domains Responsible for the entities; exposing their functionalities through Jobs
  • 41. Lucid * Domains ● Article ○ GetPublishedArticlesJob ○ SaveArticleJob ○ ValidateArticleInputJob ● CDN ○ UploadFilesToCdnJob ● HTTP ○ RespondWithJsonJob
  • 42.
  • 43. Lucid * Principles ● Controllers serve Features ● Avoid Cross-Domain Communication ● Avoid Cross-Job Communication
  • 44. Best Practices ● Standards (PHP-FIG) ○ Autoloading ○ Code Style ● Interfaces ● Components ○ Carbon ○ Intervention ● Pull Requests & ● Code Reviews on GitHub

Hinweis der Redaktion

  1. API architecture We need to use micro frameworks for APIs
  2. Laravel provides these features and it sets it apart from other PHP frameworks.
  3. Same as filters in Yii Can be defined Globally with route group
  4. Validate all requests coming from Twilio
  5. Problems DI solves are “Inversion of Control” and “Dependency Inversion Principle” Loosening dependencies by separate instantiation Depend on abstractions rather than concretions
  6. Dependency of UserRepository is injected automatically through Service Containers
  7. Service container bindings are registered in Service Providers We can replace these bindings with mock classes and testing can become simpler.
  8. Laravel uses flysystem library to provide filesystem abstraction.
  9. I guess Convention over Configuration is not specific to ORM In Laravel it has more use in ORM as compared to Ruby On Rails in which most of the framework features work on this principle
  10. Architecture: Outcome depends on how structures are connected. (DNA -> dinosaur) Old/legacy projects like Shredd/MTSobek New developer needs to understand where each piece of code resides
  11. How Structures (Classes) like any service connected to other part of our code High level or Top level view. An expression of a Viewpoint. Communicate Structures Large application code New developer MVC example
  12. Why use architecture Utility and Helper Classes Single Responsibility Principle
  13. Thin controller
  14. Autoloading (PSR-4) Code Style (PSR-2)