Skip to content

hnrazevedo/Viewer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Viewer @HnrAzevedo

Maintainer Latest Version Scrutinizer Code Quality Build Status Software License PHP from Packagist Total Downloads

The Viewer is a simple component of managing the MVC project visualization layer. It can be used individually statically or together as middleware. Its author is not a professional in the development area, just someone in the Technology area who is improving his knowledge.

O Viewer é um simples componente de administração da camada de visualização de projetos MVC. Ele pode ser utilizado de forma individualmente de forma estática ou em conjunto como middleware. Seu autor não é profissional da área de desenvolvimento, apenas alguem da área de Tecnologia que está aperfeiçoando seus conhecimentos.

Highlights

  • Easy to set up (Fácil de configurar)
  • Follows standard PSR-15 (Segue padrão o PSR-15)
  • Composer ready (Pronto para o composer)

Installation

Viewer is available via Composer:

"hnrazevedo/Viewer": "^2.0"

or in at terminal

composer require hnrazevedo/Viewer

Methods

Extensions

  • View files: view.php
  • Imported files: inc.php

Basic use

require __DIR__.'/../vendor/autoload.php';

use HnrAzevedo\Viewer\Viewer;

/**
 * Render method:
 * string $filename
 * ?array $data
 * ?bool $return
*/

Viewer::path(__DIR__.'/Views/') 
      ->render('default');    

Return rendering

To return the content in a variable instead of being rendered, use the optional parameter of the render method

Para retornar em uma váriavel o conteúdo ao invés de ser renderizado, utilize o parametro opcional do método render

require __DIR__.'/../vendor/autoload.php';

use HnrAzevedo\Viewer\Viewer;

/**
 * Render method:
 * string $filename
 * ?array $data
 * ?bool $return
*/

$html = Viewer::path(__DIR__.'/Views/')->render('default', null, true);    

Data transfer between the view and the controller

require __DIR__.'/../vendor/autoload.php';

use HnrAzevedo\Viewer\Viewer;

$data = [
    'parameter'=>
        [
            'param1' => 1,
            'param2' => 'param2Value'  
            'param3' => '<a href="#">Parameter3</a>'  
        ]    
    ];

Viewer::path(__DIR__.'/Views/')
      ->render('default', $data);

Returning data in the view

The htmlspecialchars function is used by default as an escape to prevent XSS attacks.

É utilizado de forma padrão a função htmlspecialchars como escape para evitar ataques XSS.

Sintax:

Sintaxe:

{{ $var }} htmlspecialchars

To display information without space use the syntax:

Para exibir informações sem espace utilize a sintaxe:

{{!! $var !!}} NO htmlspecialchars

HTML file example

<html>
    {{ $parameter }}
    {{ $parameter.param2 }}
    {{ $parameter.param3 }}
    {{!! $parameter.param3 !!}}
</html>

Note: If there is no variable to replace the value defined in the view, the text will be visible

HTML file result example:

<html>
    {{ $parameter }}
    param2Value 
    <a href="#">Parameter3</a> 
    <a tag>Parameter</a tag>
</html>

Returning object properties

IMPORTANT: to return any property of an object, the property must be public, to be returned with the "get_object_vars" function, or a function with the name "getVars" must be defined, returning an array with the properties that need to be executed __get.

Models\User.php

namespace Model;

class User{
    public string $name = '';
    private string $lastname = 'Azevedo';
    private string $testValue = '123';

    public array $data = [];

    public function __construct()
    {
        $this->data = ['email','password','birth','username','testValue'];
    }

    public function getVars(): array
    {
        $vars = [];
        foreach($this->data as $var => $value){
            $vars[$var] = null;
        }
        return $vars;
    }

    public function __set(string $field, $value)
    {
        $this->data[$field] = $value;
    }

    public function __get(string $field)
    {
        return $this->data[$field];
    }
}

Example\User.php

$user = new Model\User();

$user->name = 'Henri';
$user->email = 'hnr.azevedo@gmail.com';
$user->birth = '28/09/1996';
$user->username = 'hnrazevedo';
$user->testValue = '321';

Viewer::path(__DIR__.'/Views/')->render('default', ['user'=>$user]);

default.view.php

{{ $user.name }} -> execute $user->name -> $user->name
{{ $user.email }} -> execute $user->email -> $user->__get('email')
{{ $user.bitrh }} -> execute $user->bitrh -> $user->__get('bitrh')
{{ $user.username }} -> execute $user->bitrh -> $user->__get('username')
{{ $user.lastname }} -> It is not executed, as private properties are not returned in the "get_object_vars" function
{{ $user.testValue }} -> execute $user->testValue -> $user->__get('testValue')

Result of default.view.php

Henri Azevedo 
hnr.azevedo@gmail.com 
28/09/1996 
hnrazevedo
{{ $user.lastname }}
321

Import content within the view.

NOTE: File extension inc.php

NOTE: File path is from the defined view path in question

<html>
    <body>
        <?php $this->import('../Imports/header'); ?>
        <main>
            ...
        </main>
        <?php $this->import('../Imports/footer'); ?>
    </body>
</html>

If the file is not found, in order to avoid a page break, a div results with an error message instead of include.

Caso o arquivo não seja encontrado, para não haver quebra de página, é resultado uma div com a mensagem de erro no lugar do include.

<html>
    <body>
        <div class='view error'>Component error: Impotation file does not exist: header.inc.php .</div>
        <main>
            ...
        </main>
        <footer>
            ...
        </footer>
    </body>
</html>

HTML compression

All code returned from a view or include is compressed. Thus, to avoid code problems, all comments are ignored when rendering the content.

Todo código retornado de uma view ou include é compressado. Com isto, para evitar problemas de código, todos os comentários são ignorados na renderização do conteúdo.

Source code

<html>
    <body>
        <main>
            <!-- Multi-line 
                             comment --> ...
        </main>
        <footer>
            ...
        </footer>
    </body>
    <script>
        ...; // Single line comment
        /* comments */ ...; /* comments */
        /* 
            Multi-line
            commnets
        */
        ...;
    </script>
</html>

Rendered code

<html><body><main>...</main><footer>...</footer></body><script>...;...;...;</script></html>

Support

Security: If you discover any security related issues, please email hnr.azevedo@gmail.com instead of using the issue tracker.

Se você descobrir algum problema relacionado à segurança, envie um e-mail para hnr.azevedo@gmail.com em vez de usar o rastreador de problemas.

Credits

License

The MIT License (MIT). Please see License File for more information.

About

Camada de visualização para projetos MVC PHP

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages