一般说明
当您访问 Laravel Blade 视图时,它会将其生成到一个临时文件中,因此它不必在您每次访问视图时都处理 Blade 语法。这些文件存储在app/storage/view 中,文件名是文件路径的MD5 哈希。
通常当您更改视图时,Laravel 会在下一次视图访问时自动重新生成这些文件,然后一切都会继续。这是通过filemtime() 函数比较生成文件和视图源文件的修改时间来完成的。可能在您的情况下存在问题并且临时文件没有重新生成。在这种情况下,您必须删除这些文件,以便重新生成它们。它不会伤害任何东西,因为它们是从您的视图中自动生成的,并且可以随时重新生成。它们仅用于缓存目的。
通常,它们应该会自动刷新,但是如果它们被卡住并且遇到此类问题,您可以随时删除这些文件,但正如我所说,这些应该只是极少数例外。
代码分解
以下所有代码均来自laravel/framerok/src/Illuminate/View/。我在原件上添加了一些额外的 cmets。
获取视图
从Engines/CompilerEngine.php 开始,我们有了理解机制所需的主要代码。
public function get($path, array $data = array())
{
// Push the path to the stack of the last compiled templates.
$this->lastCompiled[] = $path;
// If this given view has expired, which means it has simply been edited since
// it was last compiled, we will re-compile the views so we can evaluate a
// fresh copy of the view. We'll pass the compiler the path of the view.
if ($this->compiler->isExpired($path))
{
$this->compiler->compile($path);
}
// Return the MD5 hash of the path concatenated
// to the app's view storage folder path.
$compiled = $this->compiler->getCompiledPath($path);
// Once we have the path to the compiled file, we will evaluate the paths with
// typical PHP just like any other templates. We also keep a stack of views
// which have been rendered for right exception messages to be generated.
$results = $this->evaluatePath($compiled, $data);
// Remove last compiled path.
array_pop($this->lastCompiled);
return $results;
}
检查是否需要再生
这将在Compilers/Compiler.php 中完成。这是一个重要的功能。根据结果,将决定是否应该重新编译视图。如果这返回 false 而不是 true,则可能是视图未重新生成的原因。
public function isExpired($path)
{
$compiled = $this->getCompiledPath($path);
// If the compiled file doesn't exist we will indicate that the view is expired
// so that it can be re-compiled. Else, we will verify the last modification
// of the views is less than the modification times of the compiled views.
if ( ! $this->cachePath || ! $this->files->exists($compiled))
{
return true;
}
$lastModified = $this->files->lastModified($path);
return $lastModified >= $this->files->lastModified($compiled);
}
重新生成视图
如果视图过期,它将重新生成。在Compilers\BladeCompiler.php 中,我们看到编译器将遍历所有 Blade 关键字,最后返回一个包含已编译 PHP 代码的字符串。然后它将检查是否设置了视图存储路径并将文件保存在那里,文件名是视图文件名的 MD5 哈希。
public function compile($path)
{
$contents = $this->compileString($this->files->get($path));
if ( ! is_null($this->cachePath))
{
$this->files->put($this->getCompiledPath($path), $contents);
}
}
评估
最终在Engines/PhpEngine.php 中评估视图。它使用extract() 和include 将传递给视图的数据导入具有try 和catch 中传递路径的文件的所有异常handleViewException() 再次引发异常。还有一些输出缓冲。