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

View Laravel Package

aura/view

Lightweight PHP view/template system implementing TemplateView and TwoStepView patterns. Uses plain PHP templates (file or closure), supports helpers and sections, and has no userland dependencies. Install via Composer as aura/view.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation:

    composer require aura/view
    

    No additional dependencies are required.

  2. Basic Setup:

    use Aura\View\ViewFactory;
    
    $viewFactory = new ViewFactory();
    $view = $viewFactory->newInstance();
    
  3. First Use Case:

    • Register a template:
      $view->getViewRegistry()->set('home', __DIR__ . '/views/home.php');
      
    • Set data:
      $view->setData(['title' => 'Welcome']);
      
    • Render the view:
      echo $view->setView('home')();
      

Where to Look First

  • Documentation: Start with the README and the API docs.
  • Examples: Explore the unit tests for practical usage patterns.
  • Key Classes:
    • ViewFactory: For instantiating the View object.
    • View: Core class for rendering templates.
    • ViewRegistry/LayoutRegistry: For managing templates.
    • HelperRegistry: For registering helpers.

Implementation Patterns

Core Workflows

1. Template Rendering

  • File-based templates:
    $view->getViewRegistry()->set('template', __DIR__ . '/views/template.php');
    $view->setView('template')->setData(['user' => 'John'])->setLayout('layout');
    echo $view();
    
  • Closure-based templates (inline logic):
    $view->getViewRegistry()->set('greeting', function () {
        echo "Hello, {$this->user}!";
    });
    $view->setView('greeting')->setData(['user' => 'Jane']);
    echo $view();
    

2. Two-Step View (Layouts)

  • Register a layout:
    $view->getLayoutRegistry()->set('default', __DIR__ . '/layouts/default.php');
    
  • Use in a template:
    // In default.php:
    <html>
        <body><?= $this->getContent() ?></body>
    </html>
    
  • Render with layout:
    $view->setView('home')->setLayout('default');
    echo $view();
    

3. Helpers

  • Register a helper (e.g., for escaping or utilities):
    $view->getHelpers()->set('escape', function ($str) {
        return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    });
    
  • Use in templates:
    // In template.php:
    echo $this->escape($this->user);
    

4. Sections and Partials

  • Sections (capture output for layouts):
    // In template.php:
    $this->beginSection('sidebar');
    echo "<div>Sidebar content</div>";
    $this->endSection();
    
    // In layout.php:
    if ($this->hasSection('sidebar')) {
        echo $this->getSection('sidebar');
    }
    
  • Partials (reusable snippets):
    $view->getViewRegistry()->set('_partial', __DIR__ . '/views/_partial.php');
    // In template.php:
    echo $this->render('_partial', ['data' => 'value']);
    

5. Dynamic Layouts

  • Set layout dynamically in a template:
    // In template.php:
    $this->setLayout('admin_layout');
    

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Integration: Bind ViewFactory and View to the Laravel container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(\Aura\View\ViewFactory::class, function ($app) {
            return new \Aura\View\ViewFactory();
        });
        $this->app->bind(\Aura\View\View::class, function ($app) {
            return $app->make(\Aura\View\ViewFactory::class)->newInstance();
        });
    }
    
  2. Blade-like Usage: Override Laravel's Blade with Aura View by extending ViewServiceProvider:

    public function boot()
    {
        $view = $this->app->make(\Aura\View\View::class);
        $view->getViewRegistry()->setPaths([base_path('resources/views')]);
        // Replace Blade with Aura View in routes/controllers.
    }
    
  3. Middleware for View Setup: Use middleware to pre-load common data/helpers:

    public function handle($request, Closure $next)
    {
        $view = $this->app->make(\Aura\View\View::class);
        $view->setData(['user' => auth()->user()]);
        $view->getHelpers()->set('flash', function ($message) {
            return "<div class='alert'>$message</div>";
        });
        return $next($request);
    }
    
  4. Template Caching: Cache compiled templates (e.g., using Aura\View\TemplateLocator with a custom cache adapter):

    $view->getViewRegistry()->setLocator(new \Aura\View\TemplateLocator([
        new \Aura\View\FileLocator(__DIR__ . '/views'),
        new \Aura\View\CacheLocator($cacheAdapter, __DIR__ . '/views'),
    ]));
    

Performance Optimization

  • Pre-register templates in a service provider to avoid runtime lookups.
  • Use closures for dynamic or rarely changing templates to skip file I/O.
  • Batch data assignment with addData() to merge data efficiently.

Testing

  • Unit Test Templates:
    public function testTemplateRendering()
    {
        $view = (new ViewFactory())->newInstance();
        $view->getViewRegistry()->set('test', function () {
            return $this->data['message'];
        });
        $view->setData(['message' => 'Hello']);
        $this->assertEquals('Hello', $view->setView('test')());
    }
    
  • Mock Helpers:
    $view->getHelpers()->set('mockHelper', $this->createMock(InvokableInterface::class));
    

Gotchas and Tips

Pitfalls

  1. No Built-in Escaping:

    • Issue: Aura/View does not auto-escape output. Always manually escape dynamic content (e.g., htmlspecialchars() for HTML).
    • Fix: Use Aura\Html for helpers or create custom helpers:
      $view->getHelpers()->set('h', function ($str) {
          return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
      });
      
  2. Closure Scope Quirks:

    • Issue: Closure-based templates require explicit extract() for passed variables:
      $view->getViewRegistry()->set('partial', function (array $vars) {
          extract($vars); // Required!
          echo $name; // Now accessible.
      });
      
    • Fix: Always define a $vars parameter and use extract($vars).
  3. Layout Overrides:

    • Issue: Setting a layout in a template replaces the existing layout, not merges it.
    • Fix: Use sections to compose layouts dynamically.
  4. Template Paths:

    • Issue: Paths are not auto-resolved. Always use absolute paths or prepend setPaths():
      $view->getViewRegistry()->setPaths([base_path('resources/views')]);
      $view->getViewRegistry()->set('home', 'home'); // Resolves to `resources/views/home.php`.
      
  5. Data Overwriting:

    • Issue: setData() replaces all existing data. Use addData() to merge:
      $view->setData(['user' => 'Alice']);
      $view->addData(['role' => 'admin']); // Merges, doesn't replace.
      
  6. Helper Collisions:

    • Issue: Helpers with the same name will overwrite each other.
    • Fix: Use namespaced helpers or validate uniqueness.
  7. Sections vs. Partials:

    • Issue: Sections capture output for later use (e.g., layouts), while partials render immediately.
    • Fix: Use sections for layout composition and partials for reusable components.

Debugging Tips

  1. Template Not Found:

    • Verify paths with setPaths() and check file permissions.
    • Enable debug mode in ViewRegistry:
      $view->getViewRegistry()->setDebug(true);
      
  2. Helper Not Found:

    • Check the helper registry:
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor