PHP code example of prosopo / views

1. Go to this page and download the library: Download prosopo/views library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

prosopo / views example snippets


use Prosopo\Views\View\ViewNamespaceConfig;
use Prosopo\Views\View\ViewTemplateRenderer;
use Prosopo\Views\ViewsManager;

erer = new ViewTemplateRenderer();

// 2. Make the namespace config

$namespaceConfig = (new ViewNamespaceConfig($viewTemplateRenderer))
    ->setTemplatesRootPath(__DIR__ . './templates')
    ->setTemplateFileExtension('.blade.php');

// 3. Make the Views Manager instance:

$viewsManager = new ViewsManager();

// 4. Add the root namespace of your Template Models

$viewsManager->registerNamespace('MyPackage\Views', $namespaceConfig);

namespace MyPackage\Views;

use Prosopo\Views\BaseTemplateModel;

class EmployeeTemplateModel extends BaseTemplateModel
{
    public int $salary;
    public int $bonus;
    public CompanyTemplateModel $company;

    public function total(): int
    {
        return $this->salary + $this->bonus;
    }
}

<p>
Your month income is {{ $total() }}, 
from which {{ $salary }} is a salary, and {{ $bonus }} is a bonus.
Est. taxes: {{ $company->calcTaxes($salary) }}
</p>

<p>Company info:</p>

{!! $company !!}

$namespaceConfig = (new ViewNamespaceConfig($viewTemplateRenderer))
    ->setTemplatesRootPath(__DIR__ . './templates')
    ->setTemplateFileExtension('.blade.php');

// 3. Make the Views Manager instance:

$viewsManager = new ViewsManager();

// 4. Add the root namespace of your Template Models

$viewsManager->registerNamespace('MyPackage\Views', $namespaceConfig);

echo $viewsManager->renderModel(
    EmployeeTemplateModel::class,
    function (EmployeeTemplateModel $employee) use ($salary, $bonus) {
        $employee->salary = $salary;
        $employee->bonus = $bonus;
    }
);

$employee = $viewsManager->createModel(EmployeeTemplateModel::class);

// ...

$employee->salary = $salary;
$employee->bonus = $bonus;

// ...

echo $views->renderModel($employee);

// Tip: you can pass the callback as the second argument for both createModel() and renderModel() models
// to customize the Model properties before returning/rendering. 

namespace MyPackage\Views;

use Prosopo\Views\BaseTemplateModel;

class EmployeeTemplateModel extends BaseTemplateModel
{
    public int $salary;
    public int $bonus;
}

namespace MyPackage\Views;

use Prosopo\Views\BaseTemplateModel;
use Prosopo\Views\Interfaces\Model\TemplateModelInterface;

class EmployeeTemplateModel extends BaseTemplateModel
{
    // Use the abstract interface to accept any Model.
    public TemplateModelInterface $innerModel;
    // Use a specific class only when you want to restrict the usage to it.
    public CompanyTemplateModel $company;
}

namespace MyPackage\Views;

use Prosopo\Views\BaseTemplateModel;

class EmployeeTemplateModel extends BaseTemplateModel
{
    // approach for plain field types.
    public int $varWithCustomDefaultValue = 'custom default value';
    public Company $company;

    protected function setCustomDefaults(): void
    {
        // approach for object field types.
        $this->company = new Company();
    }
}

namespace MyPackage\Views;

use Prosopo\Views\Interfaces\Model\TemplateModelInterface;

class AnyClass implements TemplateModelInterface
{
    public function getTemplateArguments(): array
    {
        // you can fill out arguments from any source or define manually.
        return [
            'name' => 'value',
        ];
    }
}

$namespaceConfig->setModelsAsStringsInTemplates(true);

use Prosopo\Views\View\ViewNamespaceConfig;
use Prosopo\Views\View\ViewTemplateRenderer;
use Prosopo\Views\ViewsManager;

// 1. Make the Template Renderer.
// (By default it uses the built-in Blade, but you can connect any)

$viewTemplateRenderer = new ViewTemplateRenderer();

// 2. Make the namespace config

$namespaceConfig = (new ViewNamespaceConfig($viewTemplateRenderer))
    // essary only if you defined the templateErrorHandler)
$namespaceConfig->getModules()
    ->setEventDispatcher($viewTemplateRenderer->getModules()->getEventDispatcher());

// 3. Make the Views instance:

$viewsManager = new ViewsManager();

// 4. Add the root namespace of your Template Models

$viewsManager->registerNamespace('MyPackage\Views', $namespaceConfig);

// Tip: you can have multiple namespaces, and mix their Models.

echo $viewsManager->renderModel(
    EmployeeModel::class,
    function (EmployeeModel $employee) use ($salary, $bonus) {
        $employee->salary = $salary;
        $employee->bonus = $bonus;
    }
);

$employee = $viewsManager->createModel(EmployeeModel::class);

// ...

$employee->salary = $salary;
$employee->bonus = $bonus;

// ...

echo $views->renderModel($employee);

// Tip: you can still pass the callback as the second renderModel() argument
// to customize the Model properties before rendering. 

$namespaceConfig = (new ViewNamespaceConfig($viewTemplateRenderer))
    ->setTemplatesRootPath(__DIR__ . './templates')
    ->setTemplateFileExtension('.blade.php');

// 3. Make the Views Manager instance:

$viewsManager = new ViewsManager();

// 4. Add the root namespace of your Template Models

$viewsManager->registerNamespace('MyPackage\Views', $namespaceConfig);

// 1. Make a facade (for Twig or another template engine)

use Prosopo\Views\Interfaces\Template\TemplateRendererInterface;
use Prosopo\Views\View\ViewNamespaceConfig;
use Prosopo\Views\ViewsManager;

class TwigDecorator implements TemplateRendererInterface
{
    private $twig;

    public function __construct()
    {
        // todo init Twig or another engine.
    }

    public function renderTemplate(string $template, array $variables = []): string
    {
        return $this->twig->render($template, $variables);
    }
}

// 2. Define the namespace config with the facade instance

$twigDecorator = new TwigDecorator();

$namespaceConfig = (new ViewNamespaceConfig($twigDecorator))
    ->setTemplatesRootPath(__DIR__ . './templates')
    ->setTemplateFileExtension('.twig');

// 3. Make the Views:

$viewsManager = new ViewsManager();

// 4. Add the namespace (you can have multiple namespaces)

$viewsManager->registerNamespace('MyPackage\Views', $namespaceConfig);

// ...

$viewsManager->renderModel(MyTwigModel::class);

$namespaceConfig->getModules()
     // override any available module, like TemplateRenderer or Factory:
    ->setModelFactory(new MyFactory());

$viewsManager->registerNamespace('App\Twig',$configForTwigNamespace);

namespace App\Twig;

use Prosopo\Views\BaseTemplateModel;

class ButtonModel extends BaseTemplateModel {
 public string $label;
}

$viewsManager->registerNamespace('App\Blade',$configForBladeNamespace);

namespace App\Blade;

use Prosopo\Views\BaseTemplateModel;

class PopupModel extends BaseTemplateModel {
}

namespace App\Blade;

use Prosopo\Views\BaseTemplateModel;
use App\Twig\ButtonModel;

class PopupModel extends BaseTemplateModel {
 public ButtonModel $buttonModel;
}

use Prosopo\Views\View\ViewTemplateRenderer;

$viewTemplateRenderer = new ViewTemplateRenderer();

echo $viewTemplateRenderer->renderTemplate('/my-template.blade.php', [
    'var' => true
]);

use Prosopo\Views\View\ViewTemplateRenderer;
use Prosopo\Views\View\ViewTemplateRendererConfig;

$viewRendererConfig = new ViewTemplateRendererConfig();
$viewRendererConfig->setFileBasedTemplates(false);

$viewTemplateRenderer = new ViewTemplateRenderer($viewRendererConfig);

echo $viewTemplateRenderer->renderTemplate('@if($var)The variable is set.@endif', [
    'var' => true
]);

use Prosopo\Views\View\ViewTemplateRenderer;
use Prosopo\Views\View\ViewTemplateRendererConfig;

$viewRendererConfig = (new ViewTemplateRendererConfig())
// By default, the Renderer expect a file name.
// Set to false if to work with strings
    ->setFileBasedTemplates(true)
    ->setTemplateErrorHandler(function (array $eventDetails): void {
        // Can be used for logging, notifying, etc.
    })
    ->setCustomOutputEscapeCallback(function ($variable): string {
        if (
            false === is_string($variable) &&
            false === is_numeric($variable)
        ) {
            return '';
        }

        // htmlspecialchars is the default one.
        return htmlentities((string)$variable, ENT_QUOTES, 'UTF-8', false);
    })
    ->setGlobalVariables([
        'sum' => function (int $a, int $b): string {
            return (string)($a + $b);
        },
        'variable' => 'value',
    ])
    ->setEscapeVariableName('escape')
    ->setCompilerExtensionCallback(function (string $template): string {
        // note: just an example, @use is supported by default.
        return (string)preg_replace('/@use\s*\((["\'])(.*?)\1\)/s', ' use $2; 

use Prosopo\Views\Interfaces\Template\TemplateCompilerInterface;
use Prosopo\Views\View\ViewNamespaceConfig;
use Prosopo\Views\View\ViewTemplateRenderer;
use Prosopo\Views\View\ViewTemplateRendererConfig;
use Prosopo\Views\ViewsManager;

class CompilerStubForPlainPhpSupport implements TemplateCompilerInterface
{
    public function compileTemplate(string $template): string
    {
        return $template;
    }
}

// ...

$viewTemplateRendererConfig = new ViewTemplateRendererConfig();
$viewTemplateRendererConfig->getModules()
    ->setTemplateCompiler(new CompilerStubForPlainPhpSupport());

$viewTemplateRenderer = new ViewTemplateRenderer($viewTemplateRendererConfig);

$views = new ViewsManager();

$viewNamespaceConfig = new ViewNamespaceConfig($viewTemplateRenderer);
$viewNamespaceConfig
    ->setTemplatesRootPath(__DIR__ . './templates')
    ->setTemplateFileExtension('.php');

$views->registerNamespace('MyApp\Models', $viewNamespaceConfig);