Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laminas View Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laminas/laminas-view
    

    Ensure your composer.json includes "laminas/laminas-view": "^3.0".

  2. Basic View Initialization:

    use Laminas\View\View;
    use Laminas\View\Renderer\PhpRenderer;
    
    $view = new View(new PhpRenderer());
    $view->setTemplatePath('path/to/templates');
    
  3. First Render:

    $view->setVariables(['title' => 'Hello World']);
    echo $view->render('index');
    

    Create index.phtml in your template path:

    <h1><?= $this->escapeHtml($title) ?></h1>
    
  4. 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.

Implementation Patterns

Core Workflows

1. Template Rendering

  • Basic Rendering:
    $view->render('template-name', ['var1' => 'value1']);
    
  • Partial Rendering:
    $view->render('partial::header');
    
  • Template Inheritance: Use extends in child templates:
    <!-- child.phtml -->
    <?php $this->layout('layout.phtml'); ?>
    <h1><?= $this->escapeHtml($title) ?></h1>
    

2. Helper Integration

  • Built-in Helpers:
    $this->escapeHtml($userInput); // Escapes HTML
    $this->url('route-name', ['param' => 'value']); // URL generation
    $this->partial('template', ['data' => $array]); // Reusable partials
    
  • Custom Helpers:
    $helperManager = $view->getHelperPluginManager();
    $helperManager->setService('myHelper', new MyHelper());
    
    Register via config/autoload/view.global.php:
    return [
        'view_helpers' => [
            'factories' => [
                'myHelper' => MyHelperFactory::class,
            ],
        ],
    ];
    

3. View Models

  • Chaining and Composition:
    $viewModel = new \Laminas\View\Model\ViewModel(['data' => $array]);
    $viewModel->setTemplate('template.phtml');
    $viewModel->setTerminal(true); // Prevent further chaining
    $view->renderModel($viewModel);
    
  • Dynamic Variables:
    $viewModel->setVariables(['key' => 'value']);
    

4. Template Resolvers

  • Custom Paths:
    $resolver = new \Laminas\View\TemplatePathStack([
        'path1' => '/custom/path1',
        'path2' => '/custom/path2',
    ]);
    $view->setTemplatePathStack($resolver);
    
  • Priority Order: Resolver checks paths in order until a template is found.

5. Configuration

  • Global Config (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',
            ],
        ],
    ];
    
  • Runtime Overrides:
    $view->setDisplayExceptions(false);
    

Integration Tips

Laravel-Specific Adaptations

  1. 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;
        });
    }
    
  2. 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
        }
    }
    
  3. Middleware for View Data:

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $view = app('view');
        $view->setVariables(['sharedData' => $request->user()->data]);
        return $response;
    }
    
  4. Caching Templates:

    $view->setTemplateEngineOptions([
        'cache_dir' => storage_path('framework/cache/view'),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Template Not Found Errors:

    • Cause: Incorrect template_path_stack configuration or missing files.
    • Fix: Verify paths are absolute and files exist. Use template_map for static templates:
      'template_map' => [
          'error/404' => __DIR__ . '/../view/error/404.phtml',
      ],
      
  2. Helper Conflicts:

    • Cause: Duplicate helper names or incorrect registration.
    • Fix: Use unique namespaces for custom helpers (e.g., My\Helper\MyHelper).
  3. State Management in CLI:

    • Cause: View assumes HTTP state by default. CLI apps (e.g., Roadrunner) may fail.
    • Fix: Explicitly set state:
      $view->setState(\Laminas\View\View::STATE_CLI);
      
  4. Deprecated Helpers:

    • Cause: RenderChildModel and Json helpers were removed in v3.
    • Fix: Replace with partial() or custom logic for JSON rendering.
  5. Type Safety:

    • Cause: Strict types may break legacy code.
    • Fix: Enable strict_types=1 in composer.json and update type hints:
      public function __construct(public string $templatePath) {}
      

Debugging Tips

  1. Enable Debug Mode:

    $view->setDisplayExceptions(true);
    $view->setDisplayNotFoundError(true);
    
  2. Log Template Paths:

    $view->getTemplatePathStack()->getPaths(); // Debug resolver paths
    
  3. Check Helper Availability:

    if (!$view->plugin('helperName')) {
        throw new \RuntimeException('Helper not found');
    }
    
  4. Validate Variables:

    $view->setVariables([
        'safeVar' => $this->escapeHtml($userInput),
        'unsafeVar' => $userInput, // Only if escaped in template
    ]);
    

Extension Points

  1. 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);
        }
    }
    
  2. 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;
        }
    }
    
  3. 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());
        }
    }
    
  4. Helper Factories: Use Laminas\ServiceManager\Factory\FactoryInterface for dependency-injected helpers:

    class MyHelperFactory implements FactoryInterface
    {
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata