Little Small Laravel Components

Little Small Laravel Components
Photo by Frederick Yang / Unsplash

Tonight I had the good idea to profile (using this package, really suggested) Larastrap, my heavily opinionated library of Bootstrap components for Laravel. And I was surprised to find that most of the time was wasted in Illuminate\View\FileViewFinder::findInPaths() function.

With a bit of investigation I landed on a Laravel's part of code I already had to deal with: function Illuminate\View\Component::extractBladeViewFromString(), that once has been the target of a pull request rejected with no specific motivation.

This function gets a string parameter, searches for a Blade file named on the same way, and - if do not find it - tries to handle the string itself as a Blade template and to compile it. The issue: every time this function is called within a Component (all of Larastrap widgets are Blade Components), it is actually a Blade template, not a reference to a file on the filesystem, so all the time spent looking on the templates' folder is just pointless.

Overriding the function on my own Larastrap base class, just to skip the filesystem part, sped up page generation by more than 3x.

<?php

namespace MadBob\Larastrap\Base;

use Illuminate\View\Component;

abstract class Element extends Component
{
  protected function extractBladeViewFromString($contents)
  {
    $key = sprintf('%s::%s', static::class, $contents);
    
    if (isset(static::$bladeViewCache[$key])) {
      return static::$bladeViewCache[$key];
    }
    
    return static::$bladeViewCache[$key] = $this->createBladeViewFromString($this->factory(), $contents);
  }
}