H
H
Hazrat Hajikerimov2014-10-29 21:59:18
PHP
Hazrat Hajikerimov, 2014-10-29 21:59:18

Is the implementation of templating bad and will it reduce the performance of the PHP project in general?

I needed a template engine, but only a simple one, without any heavy Smarty and Twig (PHP itself is a template engine).
In general, the Controller turned to the module, it worked out its own and now it's time to wrap it in a template:

<?

class controller {
    static $class = false;

    static function run (){

        //  Маршрутизация

        Router::router();
        self::$class = Router::$module;

        // Шаблонизатор
        self::show();
    }

    static function show (){

        $data = array(
            'title'  => meta::$title,
            'descr'  => meta::$descr,
            'key'    => meta::$key,
            'css'    => css::style(),
            'js'     => js::getJs(),
            'header' => Header::show(),
            'buffer' => call_user_func(self::$class.'::show'),
            'footer' => Footer::show(),
            'other'  => ''
        );

        view::tpl('index',$data);
    }
}

As noted, everything is processed and stored in the $data array
and then the view class method does the following, I will only show the essence:
foreach ($data as $var => $value){
            str_replace("{$var}", $value, $tpl);
        }

Basically swaps {$var} with $value.
Everything works, the average project execution time is: 0.0165019035339
I have a certain feeling that I am doing poorly by executing all the heavy scripts in the array, does this affect performance? Or would it be better to pass all this as a string and then use eval() when passing through the array?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RUgaleFF, 2014-10-29
@hazratgs

Yes, it's very bad. I propose two solutions:
1. Like yours, just use the strtr function:
2. Render using require wrapped in ob_start(); and ob_end(); Extract variables from the array using extract() and work with pure variables in the template file. For example:

$data = ['var1' => 1, 'var2' => 2];
View::render('index', $data);

view::render:
extract($data);
require($viewFile);

view file:
<div class="container">
<?php echo $var1; ?>
<?=$var2 ?>
</div>

Actually, the second method is used in the Yii framework, so if you need a smart templating engine, then it's better to get confused, but if you need to run it a couple of times, the first option may be suitable

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question