laravel模块之配置

前言:laravel模块解读,测试是最好的解读

配置 config

config文件夹里只有一个Repository.php文件,该类实现了:

  • ArrayAccess php官方提供的对象数组化接口
  • Illuminate\Contracts\Config\Repository laravel契约中的配置接口

该类在laravel的功能可以从config()函数透露出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

if (! function_exists('config')) {
/**
* Get / set the specified configuration value.
*
* If an array is passed as the key, we will assume you want to set an array of values.
*
* @param array|string $key
* @param mixed $default
* @return mixed|\Illuminate\Config\Repository
*/
function config($key = null, $default = null)
{
if (is_null($key)) {
return app('config');
}

if (is_array($key)) {
return app('config')->set($key);
}

return app('config')->get($key, $default);
}
}
/**
* Set a given configuration value.
*
* @param array|string $key
* @param mixed $value
* @return void
*/
public function set($key, $value = null)
{
$keys = is_array($key) ? $key : [$key => $value];

foreach ($keys as $key => $value) {
Arr::set($this->items, $key, $value);
}
}

/**
* {@inheritdoc}
*/
public function get($id)
{
if ($this->has($id)) {
return $this->resolve($id);
}

throw new EntryNotFoundException;
}

可以看出配置模块主要是为了给用户通过容器方便设置获取可配置变量

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/**
* Created by PhpStorm.
* User: 小粽子
* Date: 2018/6/6
* Time: 17:54
*/

namespace Tests\Config;

use Illuminate\Config\Repository;
use PHPUnit\Framework\TestCase;

class RepositoryTest extends TestCase
{
protected $repository;
protected $config;

protected function setUp()
{
$this->repository = new Repository($this->config = [
'foo' => 'bar',
'bar' => 'baz',
'baz' => 'bat',
'null' => null,
'associate' => [
'x' => 'xxx',
'y' => 'yyy',
],
'array' => [
'aaa',
'zzz',
],
'x' => [
'z' => 'zoo',
],
]);
parent::setUp();
}

public function testGet()
{
$this->assertSame('bar', $this->repository->get('foo'));
}

public function testSet()
{
$this->repository->set('key', 'value');
$this->assertSame('value', $this->repository->get('key'));
}
}