Giter Site home page Giter Site logo

midorikocak / view Goto Github PK

View Code? Open in Web Editor NEW
1.0 2.0 0.0 65 KB

View is the V in MVC. A small library to include in your MVC projects. Allows you to separate presentation layer from the rest of your application.

License: MIT License

PHP 94.64% HTML 5.36%

view's Introduction

View

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

View is the V in MVC. A small library to include in your MVC projects. Allows you to separate presentation layer from the rest of your application.

Note: It's your responsibility to check user inputs. This library just renders templates. Nothing else.

Install

Via Composer

$ composer require midorikocak/view

Usage

Let's say you have blog post data like this:

$articleData = [
    'title' => 'Writing object oriented software is an art.',
    'sections' => [
        [
            'title' => 'Introduction',
            'content' => [
                'Some people say that you have to be genius, or man,
        but they mostly does not undertsand what is humble programming.
        Programming should be a modest person\'s craft.',
                'Generally those people does exclude others, create clickbait articles,
            they make you feel less confident.',
                'Do not care about them and just try to create things. Learn. Be hungry.',
            ],
        ],
    ],
    'created' => '2020-01-25 00:00:00',
];

And you want to render an article using template like this:

// template.php
<?php
if (isset($created) && $created !== '') {
    $datetime = strtotime($created);
    $formattedDate = date('D, j Y', $datetime);
}
?>
<article>
    <?php if ($title !== '') : ?>
    <header>
        <h2><?= $title ?></h2>
    </header>
    <?php endif; ?>
    <?php foreach ($sections as $section) : ?>
        <section>
            <?php if (isset($section['title'])) : ?>
            <h3><?= $section['title'] ?></h3>
            <?php endif; ?>
            <?php foreach ($section['content'] as $paragraph) : ?>
            <p><?= $paragraph ?></p>
            <?php endforeach; ?>
        </section>
    <?php endforeach; ?>
    <?php if ($created !== '') : ?>
    <footer>
        <time datetime="<?= $datetime ?>">
            <?= $formattedDate ?>
        </time>
    </footer>
    <?php endif; ?>
</article>

You can use default FileRenderer to extract your php files with variables. And you can render your plain php files with variables:

$renderer = new FileRenderer();
$view = new View($this->renderer);
$view->setTemplate('template.php');
echo $this->view->render($this->articleData);

This should output rendered html as this with variables rendered:

<article>
    <header>
        <h2>Writing object oriented software is an art.</h2>
    </header>
    <section>
        <h3>Introduction</h3>
        <p>Some people say that you have to be genius, or man, 
but they mostly does not undertsand what is humble programming. 
Programming should be a modest person's craft.</p>
        <p>Generally those people does exclude others, create clickbait articles, 
they make you feel less confident.</p>
        <p>Do not care about them and just try to create things. Learn. Be hungry.</p>
    </section>
    <footer>
        <time datetime="1579910400">Sat, 25 2020</time>
    </footer>
</article>

Note: Extracting variable into runtime can be unsecure.

Plain templates

If you have plain templates with placemarks as {{ someVariable }} you can use TemplateRenderer

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
<article>
    <header>
        <h2>{{ title }}</h2>
    </header>
    <section>
        <h3>{{ sectionTitle }}</h3>
        <p>{{ paragraph }}</p>
    </section>
    <footer>
        <time datetime="{{ created }}">
            {{ formatted }}
        </time>
    </footer>
</article>
</body>
</html>

To render this template using some data:

$templateRenderer = new TemplateRenderer();
$view = new View($templateRenderer);
$view->setTemplate('tests/View/plain.template.html');
$this->assertNotEmpty($view->render(
    [
        'title' => 'Object Oriented Programming',
        'sectionTitle' => 'Introduction',
        'parapgraph' => 'Writing object oriented software is an art.',
        'created' => '2020-01-25 00:00:00',
        'formatted' => 'Mon 25, 2020',
    ]
));

This should output rendered html as this with variables rendered:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Object Oriented Programming</title>
</head>
<body>
<article>
    <header>
        <h2>Object Oriented Programming</h2>
    </header>
    <section>
        <h3>Introduction</h3>
        <p></p>
    </section>
    <footer>
        <time datetime="2020-01-25 00:00:00">
            Mon 25, 2020
        </time>
    </footer>
</article>
</body>
</html>

Using Blade Templates

To use Blade templates, use the included BladeRenderer.

$bladeRenderer = new BladeRenderer('tests/View', '/tmp');
$view = new View($bladeRenderer);
$view->setTemplate('app');
echo $view->render(
    [
        'title' => 'OOP',
        'content' => 'Writing object oriented software is an art.',
    ]
);

Custom Renderers

To create your own renderer or extend the library with another renderer library, implement RendererInterface

<?php

declare(strict_types=1);

namespace midorikocak\view;

interface RendererInterface
{
    public function render(string $template, array $data): string;
}

Rendering data objects

If you have data objects that implement a toArray() method, you can use ViewableTrait with them. So in your controllers you can write code like this:

$article->template = 'tests/View/posts/post.php';
echo $article->render();

Custom Viewers in data objects

You can change the viewer object of your data object by accessing it with the viewer that you initialized using custom renderer.

$templateRenderer = new TemplateRenderer();
$view = new View($templateRenderer);

$article->view = $view;
$article->template = 'tests/View/plain.template.html';

echo $article->render();

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

view's People

Contributors

midorikocak avatar

Stargazers

Yek avatar

Watchers

 avatar  avatar

view's Issues

Method parameter name(s) may conflict with the actual template variable name in FileRenderer

extract($data, EXTR_OVERWRITE);
include $filename;

Suppose that I have filename key in data, since the $data array is extracted and forced to be overwritten, $filename variable may be overwritten by that extract call. I haven't tested yet, I may be wrong.

I've used function/closure scope before (not to leak variables in included file to global scope) to include dynamically generated filename, than pass the required variables (like filename and data array) to it without declaring their names, like that one (probably bad practice):

$renderer = function (): string {
    extract(func_get_arg(1), EXTR_OVERWRITE); // 2nd parameter holds template data array
    ob_start();
    include func_get_arg(0); // 1st parameter holds filename to be included
    return ob_get_clean();
};

echo $renderer($filename, $data);

Edit: Fixed shitty grammar & func_get_args() -> func_get_arg()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.