SlideShare ist ein Scribd-Unternehmen logo
1 von 57
Downloaden Sie, um offline zu lesen
IoC & Laravel
Dinh Hoang Long
FramgiaVN - BrSE
@dinhhoanglong91
1
Contents
● IoC
● Laravel
● Laravel Service Container
● Demo
2
IoC
Inversion of Control
3
IoC
Inversion of Control
4
“Custom written portions of program receive the flow of control from generic, reusable library”
_wikipedia
IoC
Hollywood Principle
5
“ Don’t call us, we will call you”
Example
6
Text based interface style
printf(“Enter your last name: ”);
scanf(“%s”, last_name);
printf(“Enter your first name: ”);
scanf(“%s”, first_name);
printf(“Hello %s %s”, last_name, first_name);
Linear, without inversion
Example
7
Text based interface style Graphic interface style
Enter your last name
Enter your first name
Submit
Linear, without inversion
printf(“Enter your last name: ”);
scanf(“%s”, last_name);
printf(“Enter your first name: ”);
scanf(“%s”, first_name);
printf(“Hello %s %s”, last_name, first_name);
Control is inverted
$("#submit").click(function() {
alert("Hello " + $("#last_name").val()
+ " " + $("#first_name").val());
});
Example
8
Text based interface style
Enter your last name
Enter your first name
Submit
● Everything is ordered - Sequential procedure
● You call library function to control the flow of
your program
Graphic interface style
printf(“Enter your last name: ”);
scanf(“%s”, last_name);
printf(“Enter your first name: ”);
scanf(“%s”, first_name);
printf(“Hello %s %s”, last_name, first_name);
Example
9
Text based interface style
Enter your last name
Enter your first name
Submit
● You register subroutine for item (button)
● Framework invokes your defined subroutine when
button is clicked
● Everything is ordered - Sequential procedure
● You call library function to control the flow of
your program
Graphic interface style
printf(“Enter your last name: ”);
scanf(“%s”, last_name);
printf(“Enter your first name: ”);
scanf(“%s”, first_name);
printf(“Hello %s %s”, last_name, first_name);
Is IoC implemented by only event?
10
Is IoC implemented by only event?
11
NO
IoC is general term
12
IoC
Callback Observer Template
Method
Service
Locator
Dependency
Injection
IoC is general term
13
IoC
Callback Observer Template
Method
Service
Locator
Dependency
Injection
PHP programmer must know it
14
● Software design pattern
● Implements inversion of control using contextualized lookup
● Pass dependency (service) to a object (client) that would use it
Dependency Injection (DI)
Dependency Injection (DI)
15
Basic Approach
class Foo {
private $bar;
public function __construct() {
$this->bar = new Bar();
}
}
$foo = new Foo();
Without DI
class Foo {
private $bar;
public function __construct(Bar $bar) {
$this->bar = $bar
}
}
$bar = new Bar();
$foo = new Foo($bar);
With DI
16
Dependency Injection (DI)
What is inverted?
Why is it a type of IoC?
17
Dependency Injection (DI)
What is inverted?
Why is it a type of IoC?
Without DI
Object creates dependency directly
With DI
Other service creates dependency and inject it into your object
Dependency Injection (DI)
18
Basic Approach
Without DI With DI
Main
Foo
Bar
create
create
create
Bin
Main
Bin
Bar
create
Foo
create
create
19
Advantages of IoC & DI
● Allow program design to be loosely coupled
● Focus module on the task it is designed for
● Prevent side effects when replacing module
● Easier to run unit test by using mock objects
20
Advantages of IoC & DI
● Allow program design to be loosely coupled
● Focus module on the task it is designed for
● Prevent side effects when replacing module
● Easier to run unit test by using mock objects
In short
Allow design to follow
Dependency Inversion Principle
and
Single Responsibility Principle
Laravel
21
Image: sitepoint.com
The most popularity PHP Framework
Powerful Features
22
● Routing
● RESTFul
● Middleware
● Eloquent
● Migration
● Seeding
● Artisan Console
You should learn all of them!
What make Laravel so powerful?
23
24
Laravel Service Container
25
Laravel Service Container
Laravel 4.2
IoC Container
Laravel 5.1
Service Container
26
Is Laravel powerful because it uses IoC?
Is Laravel powerful because it has IoC Container?
27
Does Laravel use IoC?
● IoC is basic characteristic of Framework
● The methods defined by the user
○ will often be called from within the framework
○ rather than from the user’s application code
● IoC made Framework different from Library
28
Framework vs Library
$day = Carbon::now();
$day->addDays(1);
$day->subYears(2);
You call library
Route::get(‘/’, ‘HomeController@index’);
class HomeController extends Controller {
public function index() {
return view('index');
}
}
Framework calls you
Remember Hollywood principle?
“Don’t call us, we will call you”
29
IoC is basic characteristic of framework
Laravel is a framework
So
Obviously, Laravel uses IoC
30
Is Laravel powerful because it use IoC?
Is Laravel powerful because it has IoC Container?
31
Is Laravel powerful because it use IoC?
Is Laravel powerful because it has IoC Container?
NO
IoC is basic characteristic of a framework,
Laravel is not powerful because of using it
32
Really?
33
Maybe
“...saying that these lightweight containers are special
because they use inversion of control
is like saying my car is special because it has wheels.”
_Martin Fowler
34
But wait!
“What aspect of control are they inverting”?
35
But wait!
“What aspect of control are they inverting”?
● Basic characteristic of framework to control flow -> YES, of course
36
But wait!
“What aspect of control are they inverting”?
● Basic characteristic of framework to control flow -> YES, of course
● Dependency Injection -> YES, it is excellent
37
Take a look
class Foo {
private $barRepository;
public function __construct(AppRepositoriesBarRepository $barRepository) {
$this->barRepository = $barRepository;
}
}
$foo = App::make(Foo::class);
38
Take a look
class Foo {
private $barRepository;
public function __construct(AppRepositoriesBarRepository $barRepository) {
$this->barRepository = $barRepository;
}
}
$foo = App::make(Foo::class);
You don’t have to create $barRepository in main function,
Service container automatically does it
and inject to class constructor!
39
Automatically inject dependency to constructor
is the most powerful function
of Laravel Service Container
40
Service Container Usage
Bind class or interface
App::bind('Foo', function($app) {
return new Foo();
});
App::bind('BarInterface', function($app) {
return new ConcreteBar();
});
41
Service Container Usage
Bind singleton
App::singleton('FooInterface', function($app) {
return new Foo($app['bar']);
});
Yes, Singleton Design
Pattern
42
Service Container Usage
Bind instance
$foo = new ConcreteFoo(new Bar());
App::instance('FooInterface', $foo);
43
Service Container Usage
Resolve directly
$foo = App::make('foo');
$foo = $this->app['foo'];
Like Service Locator
44
Service Container Usage
Resolve via type hinting
class Foo {
private $bar;
public function __construct(BarInterface $bar) {
$this->bar = $bar;
}
}
Yes, Dependency Injection
45
Service Container is very powerful
What make it possible?
46
Laravel Service Container
47
PHP Reflection API
48
PHP Reflection API
● classes
● interfaces
● functions
● extensions
● doc comments
Add the ability to reverse-enginee
49
PHP Reflection API
/**
* @param Bar $bar
*/
class Foo {
private $bar;
public function __construct(Bar $bar) {
$this->bar = $bar;
}
}
$reflection = new ReflectionClass('Foo');
echo $reflection->getName();
// Foo
Get Class Name
50
PHP Reflection API
/**
* @param Bar $bar
*/
class Foo {
private $bar;
public function __construct(Bar $bar) {
$this->bar = $bar;
}
}
$reflection = new ReflectionClass('Foo');
print_r($reflection->getConstructor());
// ReflectionMethod Object (
// [name] => __construct
// [class] => Foo
// )
Get Constructor
51
PHP Reflection API
/**
* @param Bar $bar
*/
class Foo {
private $bar;
public function __construct(Bar $bar) {
$this->bar = $bar;
}
}
$reflection = new ReflectionClass('Foo');
echo $reflection->getConstructor()->getParameters()[0]->getClass()->getName();
// Bar
Get class name of constructor’s first parameter
52
Now, can you figure out how
Laravel Service Container works?
53
Summary
● IoC is generic term meaning that the control flow of application is
managed by generic, reusable library rather than by application code
● IoC can be implemented in several ways: event callbacks, service
locators, template methods, observer patterns,...
54
Summary
● DI is a form of IoC, a design pattern in which dependencies of a
class are created outside of classes and injected into class
● The main advantage of IoC and DI is to allow program design to be
loosely coupled
55
Summary
● IoC Container is implemented based on IoC design principle and
Dependency Injection design pattern
● Laravel uses Reflection API to implement Service Container
56
DEMO
● Laravel Reflection API
● Laravel Service Container
57
References
● Wikipedia - Inversion of control https://en.wikipedia.org/wiki/Inversion_of_control
● Wikipedia - Dependency injection https://en.wikipedia.org/wiki/Dependency_injection
● Martin Fowler - Inversion of Control Containers and the Dependency Injection pattern http://www.martinfowler.com/articles/injection.html
● Martin Fowler - InversionOfControl http://martinfowler.com/bliki/InversionOfControl.html
● PHP-DI Understanding Dependency Injection http://php-di.org/doc/understanding-di.html
● Code Project - Dependency Injection vs Inversion of Control http://www.codeproject.com/Articles/592372/Dependency-Injection-DI-vs-
Inversion-of-Control-IO
● Laravel - Service Container https://laravel.com/docs/5.1/container

Weitere ähnliche Inhalte

Was ist angesagt?

Don't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo EditionDon't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo EditionAnthony Ferrara
 
Don't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHPDon't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHPAnthony Ferrara
 
Testing untestable code - PHPBNL11
Testing untestable code - PHPBNL11Testing untestable code - PHPBNL11
Testing untestable code - PHPBNL11Stephan Hochdörfer
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPRobertGonzalez
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
C# 6.0 Introduction
C# 6.0 IntroductionC# 6.0 Introduction
C# 6.0 IntroductionOlav Haugen
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - IntroductionŁukasz Biały
 
Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Stephan Hochdörfer
 
Testing untestable code - phpconpl11
Testing untestable code - phpconpl11Testing untestable code - phpconpl11
Testing untestable code - phpconpl11Stephan Hochdörfer
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code PrinciplesYeurDreamin'
 
Mashups with Drupal and QueryPath
Mashups with Drupal and QueryPathMashups with Drupal and QueryPath
Mashups with Drupal and QueryPathMatt Butcher
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
How to get along with implicits
How to get along with implicits How to get along with implicits
How to get along with implicits Taisuke Oe
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)servicesRafael Winterhalter
 
How to improve the quality of your TYPO3 extensions
How to improve the quality of your TYPO3 extensionsHow to improve the quality of your TYPO3 extensions
How to improve the quality of your TYPO3 extensionsChristian Trabold
 

Was ist angesagt? (20)

Don't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo EditionDon't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo Edition
 
Don't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHPDon't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHP
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Testing untestable code - PHPBNL11
Testing untestable code - PHPBNL11Testing untestable code - PHPBNL11
Testing untestable code - PHPBNL11
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHP
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
C# 6.0 Introduction
C# 6.0 IntroductionC# 6.0 Introduction
C# 6.0 Introduction
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - Introduction
 
Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010
 
C#.net evolution part 2
C#.net evolution part 2C#.net evolution part 2
C#.net evolution part 2
 
Testing untestable code - phpconpl11
Testing untestable code - phpconpl11Testing untestable code - phpconpl11
Testing untestable code - phpconpl11
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Mashups with Drupal and QueryPath
Mashups with Drupal and QueryPathMashups with Drupal and QueryPath
Mashups with Drupal and QueryPath
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Java Basics
Java BasicsJava Basics
Java Basics
 
How to get along with implicits
How to get along with implicits How to get along with implicits
How to get along with implicits
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
 
How to improve the quality of your TYPO3 extensions
How to improve the quality of your TYPO3 extensionsHow to improve the quality of your TYPO3 extensions
How to improve the quality of your TYPO3 extensions
 
Migrating to PHP 7
Migrating to PHP 7Migrating to PHP 7
Migrating to PHP 7
 

Ähnlich wie IoC&Laravel

invokedynamic for Mere Mortals [Code One 2019]
invokedynamic for Mere Mortals [Code One 2019]invokedynamic for Mere Mortals [Code One 2019]
invokedynamic for Mere Mortals [Code One 2019]David Buck
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patternsOlivier Bacs
 
From Android NDK To AOSP
From Android NDK To AOSPFrom Android NDK To AOSP
From Android NDK To AOSPMin-Yih Hsu
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Anton Arhipov
 
Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?devObjective
 
Creating Clean Code with AOP (WebExpo 2010)
Creating Clean Code with AOP (WebExpo 2010)Creating Clean Code with AOP (WebExpo 2010)
Creating Clean Code with AOP (WebExpo 2010)Robert Lemke
 
Prairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API ResponsesPrairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API Responsesdarrelmiller71
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Jacob Kaplan-Moss
 
Towards JVM Dynamic Languages Toolchain
Towards JVM Dynamic Languages ToolchainTowards JVM Dynamic Languages Toolchain
Towards JVM Dynamic Languages ToolchainAttila Szegedi
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Ray Ploski
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkSeven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkRed Hat Developers
 
"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta Semenistyi"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta SemenistyiBinary Studio
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 

Ähnlich wie IoC&Laravel (20)

invokedynamic for Mere Mortals [Code One 2019]
invokedynamic for Mere Mortals [Code One 2019]invokedynamic for Mere Mortals [Code One 2019]
invokedynamic for Mere Mortals [Code One 2019]
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patterns
 
From Android NDK To AOSP
From Android NDK To AOSPFrom Android NDK To AOSP
From Android NDK To AOSP
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
 
Future of PHP
Future of PHPFuture of PHP
Future of PHP
 
Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Dependency injectionpreso
Dependency injectionpresoDependency injectionpreso
Dependency injectionpreso
 
Creating Clean Code with AOP (WebExpo 2010)
Creating Clean Code with AOP (WebExpo 2010)Creating Clean Code with AOP (WebExpo 2010)
Creating Clean Code with AOP (WebExpo 2010)
 
Compose Camp Session 1.pdf
Compose Camp Session 1.pdfCompose Camp Session 1.pdf
Compose Camp Session 1.pdf
 
Prairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API ResponsesPrairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API Responses
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 
Towards JVM Dynamic Languages Toolchain
Towards JVM Dynamic Languages ToolchainTowards JVM Dynamic Languages Toolchain
Towards JVM Dynamic Languages Toolchain
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkSeven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
 
"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta Semenistyi"JS: the right way" by Mykyta Semenistyi
"JS: the right way" by Mykyta Semenistyi
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 

Kürzlich hochgeladen (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

IoC&Laravel

  • 1. IoC & Laravel Dinh Hoang Long FramgiaVN - BrSE @dinhhoanglong91 1
  • 2. Contents ● IoC ● Laravel ● Laravel Service Container ● Demo 2
  • 4. IoC Inversion of Control 4 “Custom written portions of program receive the flow of control from generic, reusable library” _wikipedia
  • 5. IoC Hollywood Principle 5 “ Don’t call us, we will call you”
  • 6. Example 6 Text based interface style printf(“Enter your last name: ”); scanf(“%s”, last_name); printf(“Enter your first name: ”); scanf(“%s”, first_name); printf(“Hello %s %s”, last_name, first_name); Linear, without inversion
  • 7. Example 7 Text based interface style Graphic interface style Enter your last name Enter your first name Submit Linear, without inversion printf(“Enter your last name: ”); scanf(“%s”, last_name); printf(“Enter your first name: ”); scanf(“%s”, first_name); printf(“Hello %s %s”, last_name, first_name); Control is inverted $("#submit").click(function() { alert("Hello " + $("#last_name").val() + " " + $("#first_name").val()); });
  • 8. Example 8 Text based interface style Enter your last name Enter your first name Submit ● Everything is ordered - Sequential procedure ● You call library function to control the flow of your program Graphic interface style printf(“Enter your last name: ”); scanf(“%s”, last_name); printf(“Enter your first name: ”); scanf(“%s”, first_name); printf(“Hello %s %s”, last_name, first_name);
  • 9. Example 9 Text based interface style Enter your last name Enter your first name Submit ● You register subroutine for item (button) ● Framework invokes your defined subroutine when button is clicked ● Everything is ordered - Sequential procedure ● You call library function to control the flow of your program Graphic interface style printf(“Enter your last name: ”); scanf(“%s”, last_name); printf(“Enter your first name: ”); scanf(“%s”, first_name); printf(“Hello %s %s”, last_name, first_name);
  • 10. Is IoC implemented by only event? 10
  • 11. Is IoC implemented by only event? 11 NO
  • 12. IoC is general term 12 IoC Callback Observer Template Method Service Locator Dependency Injection
  • 13. IoC is general term 13 IoC Callback Observer Template Method Service Locator Dependency Injection PHP programmer must know it
  • 14. 14 ● Software design pattern ● Implements inversion of control using contextualized lookup ● Pass dependency (service) to a object (client) that would use it Dependency Injection (DI)
  • 15. Dependency Injection (DI) 15 Basic Approach class Foo { private $bar; public function __construct() { $this->bar = new Bar(); } } $foo = new Foo(); Without DI class Foo { private $bar; public function __construct(Bar $bar) { $this->bar = $bar } } $bar = new Bar(); $foo = new Foo($bar); With DI
  • 16. 16 Dependency Injection (DI) What is inverted? Why is it a type of IoC?
  • 17. 17 Dependency Injection (DI) What is inverted? Why is it a type of IoC? Without DI Object creates dependency directly With DI Other service creates dependency and inject it into your object
  • 18. Dependency Injection (DI) 18 Basic Approach Without DI With DI Main Foo Bar create create create Bin Main Bin Bar create Foo create create
  • 19. 19 Advantages of IoC & DI ● Allow program design to be loosely coupled ● Focus module on the task it is designed for ● Prevent side effects when replacing module ● Easier to run unit test by using mock objects
  • 20. 20 Advantages of IoC & DI ● Allow program design to be loosely coupled ● Focus module on the task it is designed for ● Prevent side effects when replacing module ● Easier to run unit test by using mock objects In short Allow design to follow Dependency Inversion Principle and Single Responsibility Principle
  • 21. Laravel 21 Image: sitepoint.com The most popularity PHP Framework
  • 22. Powerful Features 22 ● Routing ● RESTFul ● Middleware ● Eloquent ● Migration ● Seeding ● Artisan Console You should learn all of them!
  • 23. What make Laravel so powerful? 23
  • 25. 25 Laravel Service Container Laravel 4.2 IoC Container Laravel 5.1 Service Container
  • 26. 26 Is Laravel powerful because it uses IoC? Is Laravel powerful because it has IoC Container?
  • 27. 27 Does Laravel use IoC? ● IoC is basic characteristic of Framework ● The methods defined by the user ○ will often be called from within the framework ○ rather than from the user’s application code ● IoC made Framework different from Library
  • 28. 28 Framework vs Library $day = Carbon::now(); $day->addDays(1); $day->subYears(2); You call library Route::get(‘/’, ‘HomeController@index’); class HomeController extends Controller { public function index() { return view('index'); } } Framework calls you Remember Hollywood principle? “Don’t call us, we will call you”
  • 29. 29 IoC is basic characteristic of framework Laravel is a framework So Obviously, Laravel uses IoC
  • 30. 30 Is Laravel powerful because it use IoC? Is Laravel powerful because it has IoC Container?
  • 31. 31 Is Laravel powerful because it use IoC? Is Laravel powerful because it has IoC Container? NO IoC is basic characteristic of a framework, Laravel is not powerful because of using it
  • 33. 33 Maybe “...saying that these lightweight containers are special because they use inversion of control is like saying my car is special because it has wheels.” _Martin Fowler
  • 34. 34 But wait! “What aspect of control are they inverting”?
  • 35. 35 But wait! “What aspect of control are they inverting”? ● Basic characteristic of framework to control flow -> YES, of course
  • 36. 36 But wait! “What aspect of control are they inverting”? ● Basic characteristic of framework to control flow -> YES, of course ● Dependency Injection -> YES, it is excellent
  • 37. 37 Take a look class Foo { private $barRepository; public function __construct(AppRepositoriesBarRepository $barRepository) { $this->barRepository = $barRepository; } } $foo = App::make(Foo::class);
  • 38. 38 Take a look class Foo { private $barRepository; public function __construct(AppRepositoriesBarRepository $barRepository) { $this->barRepository = $barRepository; } } $foo = App::make(Foo::class); You don’t have to create $barRepository in main function, Service container automatically does it and inject to class constructor!
  • 39. 39 Automatically inject dependency to constructor is the most powerful function of Laravel Service Container
  • 40. 40 Service Container Usage Bind class or interface App::bind('Foo', function($app) { return new Foo(); }); App::bind('BarInterface', function($app) { return new ConcreteBar(); });
  • 41. 41 Service Container Usage Bind singleton App::singleton('FooInterface', function($app) { return new Foo($app['bar']); }); Yes, Singleton Design Pattern
  • 42. 42 Service Container Usage Bind instance $foo = new ConcreteFoo(new Bar()); App::instance('FooInterface', $foo);
  • 43. 43 Service Container Usage Resolve directly $foo = App::make('foo'); $foo = $this->app['foo']; Like Service Locator
  • 44. 44 Service Container Usage Resolve via type hinting class Foo { private $bar; public function __construct(BarInterface $bar) { $this->bar = $bar; } } Yes, Dependency Injection
  • 45. 45 Service Container is very powerful What make it possible?
  • 48. 48 PHP Reflection API ● classes ● interfaces ● functions ● extensions ● doc comments Add the ability to reverse-enginee
  • 49. 49 PHP Reflection API /** * @param Bar $bar */ class Foo { private $bar; public function __construct(Bar $bar) { $this->bar = $bar; } } $reflection = new ReflectionClass('Foo'); echo $reflection->getName(); // Foo Get Class Name
  • 50. 50 PHP Reflection API /** * @param Bar $bar */ class Foo { private $bar; public function __construct(Bar $bar) { $this->bar = $bar; } } $reflection = new ReflectionClass('Foo'); print_r($reflection->getConstructor()); // ReflectionMethod Object ( // [name] => __construct // [class] => Foo // ) Get Constructor
  • 51. 51 PHP Reflection API /** * @param Bar $bar */ class Foo { private $bar; public function __construct(Bar $bar) { $this->bar = $bar; } } $reflection = new ReflectionClass('Foo'); echo $reflection->getConstructor()->getParameters()[0]->getClass()->getName(); // Bar Get class name of constructor’s first parameter
  • 52. 52 Now, can you figure out how Laravel Service Container works?
  • 53. 53 Summary ● IoC is generic term meaning that the control flow of application is managed by generic, reusable library rather than by application code ● IoC can be implemented in several ways: event callbacks, service locators, template methods, observer patterns,...
  • 54. 54 Summary ● DI is a form of IoC, a design pattern in which dependencies of a class are created outside of classes and injected into class ● The main advantage of IoC and DI is to allow program design to be loosely coupled
  • 55. 55 Summary ● IoC Container is implemented based on IoC design principle and Dependency Injection design pattern ● Laravel uses Reflection API to implement Service Container
  • 56. 56 DEMO ● Laravel Reflection API ● Laravel Service Container
  • 57. 57 References ● Wikipedia - Inversion of control https://en.wikipedia.org/wiki/Inversion_of_control ● Wikipedia - Dependency injection https://en.wikipedia.org/wiki/Dependency_injection ● Martin Fowler - Inversion of Control Containers and the Dependency Injection pattern http://www.martinfowler.com/articles/injection.html ● Martin Fowler - InversionOfControl http://martinfowler.com/bliki/InversionOfControl.html ● PHP-DI Understanding Dependency Injection http://php-di.org/doc/understanding-di.html ● Code Project - Dependency Injection vs Inversion of Control http://www.codeproject.com/Articles/592372/Dependency-Injection-DI-vs- Inversion-of-Control-IO ● Laravel - Service Container https://laravel.com/docs/5.1/container