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; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by this article
https://laravel-news.com/faster-laravel-optimizations
and Twitter discussion:
https://twitter.com/dgurock/status/1577314908982706176