laminas/laminas-view
Laminas View provides flexible PHP view rendering for Laminas and other apps, including template resolvers, helpers, and multiple renderer options (PhpRenderer, JSON, etc.). Build reusable layouts and partials, manage view models, and integrate with MVC or standalone stacks.
Installation:
composer require laminas/laminas-view
Ensure your composer.json includes "laminas/laminas-view": "^3.0".
Basic View Initialization:
use Laminas\View\View;
use Laminas\View\Renderer\PhpRenderer;
$view = new View(new PhpRenderer());
$view->setTemplatePath('path/to/templates');
First Render:
$view->setVariables(['title' => 'Hello World']);
echo $view->render('index');
Create index.phtml in your template path:
<h1><?= $this->escapeHtml($title) ?></h1>
Key Files to Explore:
src/View.php: Core view logic.src/Renderer/PhpRenderer.php: Default template engine.src/HelperPluginManager.php: Helper management.docs/ directory: Migration guides and usage examples.$view->render('template-name', ['var1' => 'value1']);
$view->render('partial::header');
extends in child templates:
<!-- child.phtml -->
<?php $this->layout('layout.phtml'); ?>
<h1><?= $this->escapeHtml($title) ?></h1>
$this->escapeHtml($userInput); // Escapes HTML
$this->url('route-name', ['param' => 'value']); // URL generation
$this->partial('template', ['data' => $array]); // Reusable partials
$helperManager = $view->getHelperPluginManager();
$helperManager->setService('myHelper', new MyHelper());
Register via config/autoload/view.global.php:
return [
'view_helpers' => [
'factories' => [
'myHelper' => MyHelperFactory::class,
],
],
];
$viewModel = new \Laminas\View\Model\ViewModel(['data' => $array]);
$viewModel->setTemplate('template.phtml');
$viewModel->setTerminal(true); // Prevent further chaining
$view->renderModel($viewModel);
$viewModel->setVariables(['key' => 'value']);
$resolver = new \Laminas\View\TemplatePathStack([
'path1' => '/custom/path1',
'path2' => '/custom/path2',
]);
$view->setTemplatePathStack($resolver);
config/autoload/view.global.php):
return [
'view_manager' => [
'display_not_found_error' => true,
'display_exceptions' => true,
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
];
$view->setDisplayExceptions(false);
Service Provider Setup:
use Laminas\View\View;
use Laminas\View\Renderer\PhpRenderer;
public function register()
{
$this->app->singleton('view', function ($app) {
$view = new View(new PhpRenderer());
$view->setTemplatePath($app['path.to.templates']);
return $view;
});
}
Blade-Like Integration:
Use PhpRenderer with Laravel’s Blade directives by extending the renderer:
class LaravelPhpRenderer extends PhpRenderer
{
public function __construct()
{
parent::__construct();
$this->setEscapeHtml(false); // Blade handles escaping
}
}
Middleware for View Data:
public function handle($request, Closure $next)
{
$response = $next($request);
$view = app('view');
$view->setVariables(['sharedData' => $request->user()->data]);
return $response;
}
Caching Templates:
$view->setTemplateEngineOptions([
'cache_dir' => storage_path('framework/cache/view'),
]);
Template Not Found Errors:
template_path_stack configuration or missing files.template_map for static templates:
'template_map' => [
'error/404' => __DIR__ . '/../view/error/404.phtml',
],
Helper Conflicts:
My\Helper\MyHelper).State Management in CLI:
View assumes HTTP state by default. CLI apps (e.g., Roadrunner) may fail.$view->setState(\Laminas\View\View::STATE_CLI);
Deprecated Helpers:
RenderChildModel and Json helpers were removed in v3.partial() or custom logic for JSON rendering.Type Safety:
strict_types=1 in composer.json and update type hints:
public function __construct(public string $templatePath) {}
Enable Debug Mode:
$view->setDisplayExceptions(true);
$view->setDisplayNotFoundError(true);
Log Template Paths:
$view->getTemplatePathStack()->getPaths(); // Debug resolver paths
Check Helper Availability:
if (!$view->plugin('helperName')) {
throw new \RuntimeException('Helper not found');
}
Validate Variables:
$view->setVariables([
'safeVar' => $this->escapeHtml($userInput),
'unsafeVar' => $userInput, // Only if escaped in template
]);
Custom Renderers:
Extend Laminas\View\Renderer\RendererInterface for non-PHP templates (e.g., Twig):
class TwigRenderer implements RendererInterface
{
public function render(string $template, array $variables = []): string
{
$twig = new \Twig\Environment($loader);
return $twig->render($template, $variables);
}
}
Template Resolver Extensions:
Implement Laminas\View\Template\TemplateResolverInterface for dynamic paths:
class DynamicResolver implements TemplateResolverInterface
{
public function resolve($name, $request = null)
{
if (strpos($name, 'dynamic::') === 0) {
return __DIR__ . '/dynamic/' . substr($name, 9) . '.phtml';
}
return null;
}
}
View Model Decorators:
Decorate ViewModel to add pre-render logic:
class DecoratedViewModel extends \Laminas\View\Model\ViewModel
{
public function __construct(array $data = [])
{
parent::__construct($data);
$this->setOption('pre_render', [$this, 'preRender']);
}
public function preRender()
{
$this->setVariable('processedData', $this->processData());
}
}
Helper Factories:
Use Laminas\ServiceManager\Factory\FactoryInterface for dependency-injected helpers:
class MyHelperFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null
How can I help you explore Laravel packages today?