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

IoC&Laravel

  • 1.
    IoC & Laravel DinhHoang Long FramgiaVN - BrSE @dinhhoanglong91 1
  • 2.
    Contents ● IoC ● Laravel ●Laravel Service Container ● Demo 2
  • 3.
  • 4.
    IoC Inversion of Control 4 “Customwritten portions of program receive the flow of control from generic, reusable library” _wikipedia
  • 5.
    IoC Hollywood Principle 5 “ Don’tcall us, we will call you”
  • 6.
    Example 6 Text based interfacestyle 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 interfacestyle 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 interfacestyle 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 interfacestyle 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 implementedby only event? 10
  • 11.
    Is IoC implementedby only event? 11 NO
  • 12.
    IoC is generalterm 12 IoC Callback Observer Template Method Service Locator Dependency Injection
  • 13.
    IoC is generalterm 13 IoC Callback Observer Template Method Service Locator Dependency Injection PHP programmer must know it
  • 14.
    14 ● Software designpattern ● 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 BasicApproach 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) Whatis inverted? Why is it a type of IoC?
  • 17.
    17 Dependency Injection (DI) Whatis 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 BasicApproach 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.
  • 22.
    Powerful Features 22 ● Routing ●RESTFul ● Middleware ● Eloquent ● Migration ● Seeding ● Artisan Console You should learn all of them!
  • 23.
    What make Laravelso powerful? 23
  • 24.
  • 25.
    25 Laravel Service Container Laravel4.2 IoC Container Laravel 5.1 Service Container
  • 26.
    26 Is Laravel powerfulbecause it uses IoC? Is Laravel powerful because it has IoC Container?
  • 27.
    27 Does Laravel useIoC? ● 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 basiccharacteristic of framework Laravel is a framework So Obviously, Laravel uses IoC
  • 30.
    30 Is Laravel powerfulbecause it use IoC? Is Laravel powerful because it has IoC Container?
  • 31.
    31 Is Laravel powerfulbecause 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.
  • 33.
    33 Maybe “...saying that theselightweight 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 aspectof control are they inverting”?
  • 35.
    35 But wait! “What aspectof control are they inverting”? ● Basic characteristic of framework to control flow -> YES, of course
  • 36.
    36 But wait! “What aspectof 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 classFoo { private $barRepository; public function __construct(AppRepositoriesBarRepository $barRepository) { $this->barRepository = $barRepository; } } $foo = App::make(Foo::class);
  • 38.
    38 Take a look classFoo { 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 dependencyto constructor is the most powerful function of Laravel Service Container
  • 40.
    40 Service Container Usage Bindclass or interface App::bind('Foo', function($app) { return new Foo(); }); App::bind('BarInterface', function($app) { return new ConcreteBar(); });
  • 41.
    41 Service Container Usage Bindsingleton App::singleton('FooInterface', function($app) { return new Foo($app['bar']); }); Yes, Singleton Design Pattern
  • 42.
    42 Service Container Usage Bindinstance $foo = new ConcreteFoo(new Bar()); App::instance('FooInterface', $foo);
  • 43.
    43 Service Container Usage Resolvedirectly $foo = App::make('foo'); $foo = $this->app['foo']; Like Service Locator
  • 44.
    44 Service Container Usage Resolvevia type hinting class Foo { private $bar; public function __construct(BarInterface $bar) { $this->bar = $bar; } } Yes, Dependency Injection
  • 45.
    45 Service Container isvery powerful What make it possible?
  • 46.
  • 47.
  • 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 youfigure out how Laravel Service Container works?
  • 53.
    53 Summary ● IoC isgeneric 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 isa 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 Containeris implemented based on IoC design principle and Dependency Injection design pattern ● Laravel uses Reflection API to implement Service Container
  • 56.
    56 DEMO ● Laravel ReflectionAPI ● 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