I have this following code that basically renders partials. However I was trying to find a way to prevent polluting $templatePath variable into the template (the variable is currently accessible from template which is not what I want). I only want $template and $viewHelper variables to be accessible in the template scope. Do you have any idea?
public function renderComponent(string $templatePath, ViewComponentEntityInterface $component): string
{
if (! file_exists($templatePath)) {
throw new RuntimeException('Incorrect component template path: ' . $templatePath);
}
$viewHelper = $this->viewHelperFactory->create();
ob_start();
try {
(static function (ViewComponentEntityInterface $template,ViewHelper $viewHelper) use ($templatePath) {
include $templatePath;
})($component, $viewHelper);
return ob_get_clean();
} catch (Throwable $e) {
ob_end_clean();
throw $e;
}
}
I tried to find something like array_shift but for single variable that would just unset the value and return it at the same time.
$tempatePathis not a variable, it's a parameter to the function. It won't be visible outside. Right?$templatePathfile. I can currently access the$templatePathvariable from within any template I render using this method because of theuse ($templatePath)which is necessary to include the template. So if I do<?php dd($templatePath); ?>in template, it dumps the value of$templatePathvariable.try { .... } catch(....) { .... }block. Is it your attempt to isolate the code inside the$templatePath? I would just useinclude $templatePath;since the method itself already isolates the code. Simple is often better, and certainly easier to read.includeis not enough because A) callingrenderComponentor any other method from template would become possible B) There are currently only variables that I want to be accessible in template except$templatePathbut to encapsulate it like this is safer because if someone decides to refactor and add more variables, they become accessible in template without explicitly passing them as function argument or theusething.renderComponent()is a part, would be reachable within the template code when you just include the template. Given the anonymous function, what if you make$templatePathan argument instead ofuseit? Then a change to it won't affect the value of$templatePathoutside the anonymous function. But I also notice that you don't use$templatePathafter you included the template, so any change won't have any effect (yet).