laravel核心

laravel的一些核心概念的总结

laravel核心概念

在route/web.php中创建两个类用于测试使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Gay
{
public function __construct(Gateway $gateway)
{
dump('gay');
}
}
class Gateway
{
public function __construct()
{
dump('gate_way');
}
}

Route::get('bind',function(Gay $gay){
dd($gay);
});

laravel通过App:bind(),首先访问绑定的方法。laravel会自动查找这个类是否通过bind进行了绑定,如果绑定了会运行bind处方法,
没有的话直接访问类的创建。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Gay
{
public function __construct(Gateway $gateway)
{
dump('gay');
}
}
class Gateway
{
public function __construct()
{
dump('gate_way');
}
}

App::bind('Gay', function () {
dump('222'); //这里会首先输出
return new Gay(new Gateway());
});

Route::get('bind',function(Gay $gay){
dd($gay);
});

serviceProvider在laravel中的使用

简单使用app方法,下面三种方法都是可以调用的。

1
2
3
4
5
6
7
8
9
10
Route::get('bind2',function(){
//直接使用new的方法创建类
$file = new \Illuminate\Filesystem\Filesystem();
$re = $file->get(__DIR__.'/api.php');
//使用app的方法进行创建类
//$re = app()->make('files')->get(__DIR__.'/api.php');
//$re = app()['files']->get(__DIR__.'/api.php');
$re = app('files')->get(__DIR__.'/api.php');
dd($re);
});

为什么使用app方法调用laravel中的类?
如果fileSystem需要多个依赖类,这样一来的话就会使调用非常的繁琐。app调用可以简便这种操作。

1
2
$file = new \Illuminate\Filesystem\Filesystem(new Foo(),new Bar(),new Test());
$re = $file->get(__DIR__.'/api.php');

laravel中通常会把绑定的代码放到serviceProvider中

文章目录
  1. 1. laravel核心概念
    1. 1.1. serviceProvider在laravel中的使用
|