Introduction
最近因為要在專案動態套用不同 Theme,所以研究了一下 Laravel Theme 大致上如何運作,基本上只研究了包含 Scripts, Styles 的部分,其他 Widget, Breadcumb 則因為沒用到所以沒有研究。
基本的 call flow
- Theme->uses()->layout() 初始化 Theme
- Theme->asset()->usePath()->add() 加入 Style, Scripts
- 最後在 blade 的部分透過 Theme::asset()->styles() 輸出 styles
實際看下面的 code flow
加入 Styles, Scripts
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
| // Theme.php
public function asset()
{
return $this->asset;
}
// Asset.php
public function __call($method, $parameters)
{
return call_user_func_array(array(static::container(), $method), $parameters);
}
// 這邊取得相對應的 AssetContainer instance
public static function container($container = 'default')
{
if ( ! isset(static::$containers[$container]))
{
static::$containers[$container] = new AssetContainer($container);
}
return static::$containers[$container];
}
// AssetContainer.php
protected function added($name, $source, $dependencies = array(), $attributes = array())
{
// skip... 這邊會串到 style 或是 script function 註冊 resources
}
// 以 script 為例
public function script($name, $source, $dependencies = array(), $attributes = array())
{
// Prepaend path to theme.
if ($this->isUsePath())
{
$source = $this->evaluatePath($this->getCurrentPath().$source);
// Reset using path.
$this->usePath(false);
}
$this->register('script', $name, $source, $dependencies, $attributes);
return $this;
}
|
最後來看如何輸出
在 Blade 內輸出 Styles, Scripts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| // 一樣透過 Asset.php 的 magic method 操作 AssetContainer
public function __call($method, $parameters)
{
return call_user_func_array(array(static::container(), $method), $parameters);
}
// AssetContainer.php
public function styles()
{
return $this->group('style');
}
protected function asset($group, $name)
{
// ... skip
return $this->html($group, $asset['source'], $asset['attributes']);
}
|