VOOZH about

URL: https://deepwiki.com/hypervel/support/5-view-layer

⇱ View Layer | hypervel/support | DeepWiki


Loading...
Menu

View Layer

The View Layer provides comprehensive templating, rendering, and localization capabilities for presenting data to users. It consists of three primary facades—View, Blade, and Lang—that work together to render HTML templates with dynamic data, compile Blade templates efficiently, and support multi-language applications.

For HTTP routing and response generation, see HTTP Layer. For data transformation into API responses, see Collections.

Architecture Overview

The View Layer is built on Hyperf's view engine with Laravel-style enhancements. The facade layer provides static access to the underlying view factory, Blade compiler, and translator services.

View Layer Component Architecture


Sources: src/Facades/View.php1-89 src/Facades/Blade.php1-53 src/Facades/Lang.php1-49 src/Js.php1-125

View Facade

The View facade provides the primary interface for rendering views and managing the view system. It resolves to Hyperf\ViewEngine\Contract\FactoryInterface.

Core Rendering Methods

MethodPurposeReturn Type
View::make(string $view, array $data, array $mergeData)Create view instance from nameViewInterface
View::file(string $path, array $data, array $mergeData)Create view from absolute pathViewInterface
View::first(array $views, array $data, array $mergeData)First existing view from arrayViewInterface
View::exists(string $view)Check if view existsbool
View::renderWhen(bool $condition, string $view, array $data)Conditionally renderstring
View::renderUnless(bool $condition, string $view, array $data)Inverse conditional renderstring
View::renderEach(string $view, array $data, string $iterator, string $empty)Render view for each itemstring

View Resolution and Namespaces

The view factory uses a finder to locate templates. Views can be referenced by name (e.g., welcome.index) or namespace (e.g., admin::dashboard.home).


Methods for namespace management:

  • View::addNamespace(string $namespace, array|string $hints) - Register paths for namespace
  • View::prependNamespace(string $namespace, array|string $hints) - Add paths to beginning
  • View::replaceNamespace(string $namespace, array|string $hints) - Replace all paths
  • View::addLocation(string $location) - Add directory to default namespace
  • View::addExtension(string $extension, string $engine, Closure $resolver) - Register file extension

Sources: src/Facades/View.php10-34

View Composers and Creators

View composers are callbacks executed before a view is rendered, allowing data to be injected dynamically. View creators execute when the view instance is created.


Registration methods:

  • View::creator(array|string $views, Closure|string $callback) - Register creator callback
  • View::composer(array|string $views, Closure|string $callback) - Register composer callback
  • View::composers(array $composers) - Register multiple composers

Sources: src/Facades/View.php50-54

Shared Data and Sections

The view factory supports sharing data across all views and managing sections for layout inheritance.

CategoryMethodsDescription
Shared Datashare($key, $value), shared($key, $default), getShared()Global data available to all views
SectionsstartSection($section, $content), stopSection($overwrite), yieldSection(), appendSection()Define and yield content sections
Section QuerieshasSection($name), sectionMissing($name), getSection($name, $default), getSections()Check section existence and retrieve content
StacksstartPush($section), stopPush(), startPrepend($section), stopPrepend(), yieldPushContent($section)Accumulate content for injection
State ManagementflushState(), flushStateIfDoneRendering(), flushSections(), flushStacks()Clear view state

Sources: src/Facades/View.php18-77

Components

The view system supports inline components for reusable template fragments.


Component methods:

  • View::startComponent(Closure|Htmlable|string $view, array $data) - Begin component with data
  • View::startComponentFirst(array $names, array $data) - Start first existing component
  • View::renderComponent() - Output the component
  • View::slot(string $name, string|null $content) - Define named slot
  • View::endSlot() - Close current slot

Sources: src/Facades/View.php45-49

Blade Facade

The Blade facade provides access to the Blade template compiler, which compiles .blade.php files into plain PHP. It resolves to Hyperf\ViewEngine\Compiler\CompilerInterface.

Compilation Process


Sources: src/Facades/Blade.php10-43

Custom Directives

Blade directives are custom template syntax compiled into PHP. The facade provides methods to register custom directives.

MethodPurpose
Blade::directive(string $name, callable $handler)Register custom directive (e.g., @datetime)
Blade::getCustomDirectives()Retrieve all registered directives
Blade::if(string $name, callable $callback)Register conditional directive (e.g., @admin)
Blade::check(string $name, ...$parameters)Check if conditional is true

Class Components

Blade supports class-based components that are automatically discovered and rendered.


Component registration methods:

  • Blade::component(string $class, string|null $alias, string $prefix) - Register single component
  • Blade::components(array $components, string $prefix) - Register multiple components
  • Blade::componentNamespace(string $namespace, string $prefix) - Register namespace for auto-discovery
  • Blade::aliasComponent(string $path, string|null $alias) - Create component alias
  • Blade::include(string $path, string|null $alias) - Register include alias
  • Blade::aliasInclude(string $path, string|null $alias) - Alias for include

Sources: src/Facades/Blade.php19-28

Compilation Configuration

MethodPurpose
Blade::setEchoFormat(string $format)Set echo output format
Blade::withDoubleEncoding()Enable double encoding for security
Blade::withoutDoubleEncoding()Disable double encoding
Blade::withoutComponentTags()Disable component tag compilation
Blade::sanitizeComponentAttribute(mixed $value)Clean component attribute value
Blade::getCompiledPath(string $path)Get compiled file path
Blade::stripParentheses(string $expression)Remove directive parentheses

Sources: src/Facades/Blade.php32-42

String Compilation

For dynamic template compilation without files:

  • Blade::compileString(string $value) - Compile template string to PHP

Lang Facade

The Lang facade provides internationalization (i18n) and localization (l10n) support. It resolves to Hypervel\Translation\Contracts\Translator.

Translation Retrieval


Translation retrieval methods:

  • Lang::get(string $key, array $replace, string|null $locale, bool $fallback) - Get translation with replacements
  • Lang::trans(string $key, array $replace, string|null $locale) - Alias for get()
  • Lang::has(string $key, string|null $locale, bool $fallback) - Check if translation exists
  • Lang::hasForLocale(string $key, string|null $locale) - Check without fallback
  • Lang::choice(string $key, Countable|array|int|float $number, array $replace, string|null $locale) - Pluralized translation
  • Lang::transChoice(string $key, Countable|array|int $number, array $replace, string|null $locale) - Alias for choice()

Sources: src/Facades/Lang.php10-33

Pluralization

The MessageSelector handles pluralization rules. Translation keys use pipe-separated variants:

'apples' => '{0} No apples|{1} One apple|[2,*] :count apples'

The choice() method selects the appropriate variant based on count.

Locale Management

MethodPurpose
Lang::locale() / Lang::getLocale()Get current locale code
Lang::setLocale(string $locale)Set active locale
Lang::getFallback()Get fallback locale code
Lang::setFallback(string $fallback)Set fallback locale
Lang::determineLocalesUsing(callable $callback)Custom locale resolution

Dynamic Translation Loading

MethodPurpose
Lang::load(string $namespace, string $group, string $locale)Load translation file
Lang::addLines(array $lines, string $locale, string $namespace)Add translations at runtime
Lang::addNamespace(string $namespace, string $hint)Register translation namespace
Lang::addPath(string $path)Add directory to search path
Lang::addJsonPath(string $path)Add JSON translation directory

Translation Management

  • Lang::getLoader() - Get translation loader instance
  • Lang::getSelector() - Get message selector for pluralization
  • Lang::setSelector(MessageSelector $selector) - Replace message selector
  • Lang::setLoaded(array $loaded) - Set loaded translations
  • Lang::setParsedKey(string $key, array $parsed) - Cache parsed key
  • Lang::flushParsedKeys() - Clear parse cache

Sources: src/Facades/Lang.php14-39

Missing Translation Handling

  • Lang::handleMissingKeysUsing(callable|null $callback) - Register callback for missing translations

String Transformation

  • Lang::stringable(callable|string $class, callable|null $handler) - Register stringable transformation for translation values

Js Helper

The Js class converts PHP data to JavaScript expressions safely for embedding in HTML templates.

Usage and Features


Construction:

  • new Js(mixed $data, int $flags, int $depth) - Create instance
  • Js::from(mixed $data, int $flags, int $depth) - Static factory method

Key methods:

  • Js::encode(mixed $data, int $flags, int $depth) - Encode to JSON with safety flags
  • toHtml() - Get JavaScript expression as string
  • __toString() - String conversion

Security Considerations

The Js class enforces specific JSON encoding flags for XSS prevention:

  • JSON_HEX_TAG - Escapes < and >
  • JSON_HEX_APOS - Escapes '
  • JSON_HEX_AMP - Escapes &
  • JSON_HEX_QUOT - Escapes "
  • JSON_THROW_ON_ERROR - Throws exception on encoding errors

These flags are combined with user-provided flags in REQUIRED_FLAGS constant.

Data Type Handling

PHP TypeJavaScript OutputExample
StringSingle-quoted string'hello world'
BackedEnumEnum value as JSJs::from(Status::Active)'active'
Array (empty)Direct output[]
Object (empty)Direct output{}
Complex array/objectJSON.parse() wrappedJSON.parse('...')
ArrayableConverts to array firstVia toArray()
JsonableUses JSON representationVia __toString()

Sources: src/Js.php1-125

View Rendering Flow

The complete flow from controller to rendered HTML involves multiple components working together.

Complete View Rendering Sequence


Sources: src/Facades/View.php1-89 src/Facades/Blade.php1-53

Integration with HTTP Layer

Views are typically returned from controllers as responses. The view rendering integrates with the HTTP response cycle.


For more details on response generation, see Request and Response.

Sources: src/Facades/View.php1-89