Last active
December 8, 2022 09:47
-
-
Save rodrigopedra/4aa1b50a3ef1464d5ff8abc3daf97ace to your computer and use it in GitHub Desktop.
Blade Optimizations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use Illuminate\Support\ServiceProvider; | |
use Illuminate\View\Compilers\BladeCompiler; | |
// @see https://laravel-news.com/faster-laravel-optimizations | |
class BladeServiceProvider extends ServiceProvider | |
{ | |
public function register() | |
{ | |
// This is needed as when compiling a string the footers are | |
// overwriten and the partials are processed before other templates | |
$this->app->singleton('partial.compiler', static fn ($app) => clone $app['blade.compiler']); | |
} | |
public function boot(BladeCompiler $blade) | |
{ | |
$blade->directive('loop', static fn ($expression) => "<?php foreach ($expression): ?>"); | |
$blade->directive('endloop', static fn () => '<?php endforeach; ?>'); | |
$blade->directive('partial', function ($expression) { | |
$parts = \explode(',', $expression, 2); | |
$parts = \array_map(static fn ($string) => \trim($string), $parts); | |
$view = \trim($parts[0], '"\''); | |
$variables = $parts[1] ?? '[]'; | |
$path = $this->app['view']->getFinder()->find($view); | |
$compiler = $this->app->make('partial.compiler'); | |
$compiledPath = $compiler->getCompiledPath($path); | |
if (! \is_file($compiledPath)) { | |
$previousPath = $compiler->getPath(); | |
$compiler->compile($path); | |
$compiler->setPath($previousPath); | |
} | |
$contents = $this->app['files']->get($compiledPath); | |
return <<<PHP | |
<?php call_user_func(function (\$__variables) use (\$__env) { | |
extract(\$__env->getShared(), EXTR_SKIP); | |
if (count(\$__variables)) extract(\$__variables); | |
?> | |
{$contents} | |
<?php }, {$variables}) ?> | |
PHP; | |
}); | |
} | |
} |
Inspired by this article
https://laravel-news.com/faster-laravel-optimizations
and Twitter discussion:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If someone figures out how to avoid having a second Blade compiler instance, please let me know :)Kind of not possible right now due to this line:
https://github.com/laravel/framework/blob/1066e3955bfd0a7877707786efbf4fda9d450502/src/Illuminate/View/Compilers/BladeCompiler.php#L241
Currently overwrites
BladeCompiler@$footer
, which breaks if a partial is added inside a template using@extends