laravel核心概念
在route/web.php中创建两个类用于测试使用1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class 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
23class 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
11
12
13
14Route::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调用可以简便这种操作。
$file = new \Illuminate\Filesystem\Filesystem(new Foo(),new Bar(),new Test());
$re = $file->get(DIR.’/api.php’);1
2
3laravel中通常会把绑定的代码放到serviceProvider中,可以通过命令行生成privider文件
```php
php artisan make:provider TestProvider
然后在TestProvider中添加register代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public function register()
{
$this->app->singleton('test',function(){
return new Test();
});
}
namespace App\Test;
class Test
{
public function sayHello()
{
dump('hello this is test;');
}
}
//在app.php得providers数组中添加
\App\Providers\TestProvider::class, //添加一个测试用的provider
//使用方法
app('test')->sayHello();
Facade在laravel中的使用
在app.php中有一个aliases数组,其中有很多项目添加的facade文件。
打开一个Mail文件可以查看背后实现的代码。1
2
3
4
5
6
7
8
9
10public static function __callStatic($method, $args)
{
$instance = static::getFacadeRoot(); //app('mail')形式
if (! $instance) {
throw new RuntimeException('A facade root has not been set.');
}
return $instance->$method(...$args);
}
下面的几种写法都是可以进行数据库配置的调用的1
2
3
4
5dump(app('config')['database']['default']);
dump(app()['config']['database']['default']);
dump(\Config::get('database.default'));
dump(app('Illuminate\Contracts\Config\Repository')['database']['default']);
dd(app('Illuminate\Config\Repository')['database']['default']);