IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Voir le flux RSS

rawsrc

PhpEcho Version 2.0.0

Note : 3 votes pour une moyenne de 3,67.
par , 04/04/2020 à 11h57 (2311 Affichages)
Salut la compagnie,

Dans le cadre de l'évolution et de l'amélioration du moteur de rendu en une classe, à savoir PhpEcho, j'ai procédé à une importante amélioration en y ajoutant la possibilité de créer et d'utiliser ses propres bouts de code afin de faciliter le rendu et à quelques autres changements dans le fonctionnement.

Le version 2.0.0 casse la compatibilité avec la version 1.0.0

Tout le principe de fonctionnement reste le même, ce qui change :
- la notation tableau de la version 1 $block['foo'] renvoyait la valeur rattachée à la clé 'foo' sans aucun échappement ; maintenant avec la version 2, la même notation renvoie toujours une valeur échappée pour les tableaux, les scalaires et les classes implémentant __toString(), pour les autres objets, il sont renvoyés tels quels.
- la notation fonction de la version 1 $block('foo') renvoyait la valeur rattachée à la clé 'foo' échappée ; maintenant avec la version 2, le notation fonction est uniquement réservée pour l'appel aux différents helpers définis par le développeur.

Comme les principes de fonctionnement restent les mêmes, je n'ai pas modifié le billet de blog initial car toutes les explications qu'il contient sont toujours d'actualité.

Je ne vais m'attarder que sur les nouveautés.

Voici le projet sur GitHub.

1 - COURT EXEMPLE

Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
$block        = new PhpEcho();
$block['foo'] = 'abc " < >';   // stock une clé-valeur dans l'instance du bloc
 
// récupération de la valeur ECHAPPÉE, par défaut, ce qui rentre dans l'instance 
// ressort échappé avec htmlspecialchars()
$x = $block['foo'];   // $x = 'abc &_quot; &lt; &gt;'
 
// pour faire un échappement à la demande : notation fonction et appel à un helper "$hsc"
$y = $block('$hsc', 'une valeur à échapper');
 
// récupération de la valeur non échappée : notation fonction et appel à un helper "$raw"
$z = $block('$raw', 'foo'); // $z = 'abc " < >'

2 - BOUTS DE CODES PERSONNALISÉS (HELPERS)

Vous avez dorénavant avec cette version, la possibilité de demander au moteur d'exécuter vos bouts de code afin de vous aider dans la génération du code de rendu.
Ces bouts de code ne sont ni plus ni moins que des Closure.
PhpEcho est fourni avec un petit jeu de helpers tous définis dans le fichier : stdHelpers.php.

Il vous est possible d'étendre les helpers définis et/ou d'ajouter les vôtres via un simple fichier comme indiqué dans le constructeur de la classe PhpEcho : self::addPathToHelperFile(__DIR__.DIRECTORY_SEPARATOR.'stdHelpers.php');
  • Chaque helper est une Closure qui peut renvoyer tout ce que vous voulez
  • Chaque helper peut être lié à une instance de PhpEcho, ainsi il sera possible d'utiliser $this-> dans son code et avoir accès à l'instance d'exécution du bloc courant
  • Chaque helper peut aussi être une fonction autonome paramétrée

À la définition d'un helper il est possible de le paramétrer avec deux constantes :
  • HELPER_BOUND_TO_CLASS_INSTANCE : pour les helpers qui sont liés à une instance d'un bloc PhpEcho
  • HELPER_RETURN_ESCAPED_DATA : pour les helpers qui renvoient du code déjà échappé pour éviter le double échappement


Dans les helpers par défaut, il y en a un qui ne se charge que de comparer 2 valeurs et si elles sont égales, il renvoie checked.
Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
$checked = function($p, $ref) use ($is_scalar): string {
    return $is_scalar($p) && $is_scalar($ref) && ((string)$p === (string)$ref) ? ' checked ' : '';
};
$helpers['$checked'] = [$checked, HELPER_RETURN_ESCAPED_DATA];
Cet helper est une fonction autonome (comparaison de 2 valeurs passées en paramètre) et comme la valeur renvoyée est juste checked, on indique avec le drapeau HELPER_RETURN_ESCAPED_DATA qu'il n'est pas nécessaire de passer la valeur renvoyée à la moulinette d'échappement.
Pour utiliser cet helper dans votre code, rien de plus simple : $this('$checked', 'valeur', 'valeur de référence').

Maintenant, regardons le helper en charge de renvoyer les valeurs non échappées au sein d'une instance de PhpEcho :
Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
$raw = function(string $key) {
    return $this->vars[$key] ?? null;
};
$helpers['$raw'] = [$raw, HELPER_RETURN_ESCAPED_DATA, HELPER_BINDED_TO_CLASS_INSTANCE];
Cet helper a besoin de pouvoir accéder à l'instance courante de PhpEcho afin d'atteindre la valeur du tableau contenue dans $vars[$key], d'où la présence du drapeau : HELPER_BOUND_TO_CLASS_INSTANCE. Par ailleurs, comme tout est automatiquement échappé par PhpEcho, on indique au moteur que cette fois ci, l'échappement n'est pas de mise dans la mesure où l'on souhaite récupérer la valeur brut.

Il existe trois moyens pour définir des helpers :

  • $helpers["$helper's id"] = $helper_closure
  • $helpers["$helper's id"] = [$helper_closure, HELPER_RETURN_ESCAPED_DATA]
  • $helpers["$helper's id"] = [$helper_closure, HELPER_RETURN_ESCAPED_DATA, HELPER_BINDED_TO_CLASS_INSTANCE]


3 - CODE LA CLASSE

Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<?php
 
namespace rawsrc\PhpEcho;
 
use ArrayAccess;
 
if ( ! defined('HELPER_BOUND_TO_CLASS_INSTANCE')) {
    define('HELPER_BOUND_TO_CLASS_INSTANCE', 1);
}
 
if ( ! defined('HELPER_RETURN_ESCAPED_DATA')) {
    define('HELPER_RETURN_ESCAPED_DATA', 2);
}
 
/**
 * PhpEcho : PHP Template engine : One class to rule them all ;-)
 *
 * @link        https://www.developpez.net/forums/blogs/32058-rawsrc/b9154/phpecho-version-2-0-0/
 * @author      rawsrc - https://www.developpez.net/forums/u32058/rawsrc/
 * @copyright   MIT License
 *
 *              Copyright (c) 2020 rawsrc
 *
 *              Permission is hereby granted, free of charge, to any person obtaining a copy
 *              of this software and associated documentation files (the "Software"), to deal
 *              in the Software without restriction, including without limitation the rights
 *              to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *              copies of the Software, and to permit persons to whom the Software is
 *              furnished to do so, subject to the following conditions:
 *
 *              The above copyright notice and this permission notice shall be included in all
 *              copies or substantial portions of the Software.
 *
 *              THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *              IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *              FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *              AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *              LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *              OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *              SOFTWARE.
 *
 *
 * @method mixed  raw($p)       Return the raw value from a PhpEcho block
 * @method mixed  hsc($p)       Escape the value in parameter (scalar, array, stringifyable)
 * @method bool   isScalar($p)
 * @method string selected($p, $ref)    Return " selected " if $p == $ref
 * @method string checked($p, $ref)     Return " checked "  if $p == $ref
 */
class PhpEcho
implements ArrayAccess
{
    /**
     * @var string
     */
    private $id = '';
    /**
     * @var array
     */
    private $vars = [];
    /**
     * Full resolved filepath to the external view file
     * @var string
     */
    private $file = '';
    /**
     * @var string
     */
    private $code = '';
    /**
     * @var array [helper's id => bound closure]
     */
    private $bound_helpers = [];
 
    /**
     * @param mixed  $file   see setFile() below
     * @param array  $vars
     * @param string $id     if empty then auto-generated
     */
    public function __construct($file = '', array $vars = [], string $id = '')
    {
        if ($file !== '') {
            $this->setFile($file);
        }
 
        if ($id === '') {
            $this->generateId();
        } else {
            $this->id = $id;
        }
 
        $this->vars = $vars;
        self::addPathToHelperFile(__DIR__.DIRECTORY_SEPARATOR.'stdHelpers.php');
    }
 
    /**
     * @param string $id
     */
    public function setId(string $id)
    {
        $this->id = $id;
    }
 
    /**
     * @return string
     */
    public function id(): string
    {
        return $this->id;
    }
 
    /**
     * Generate an unique execution id based on random_bytes()
     * Always start with a letter
     */
    public function generateId()
    {
        $this->id = chr(mt_rand(97, 122)).bin2hex(random_bytes(4));
    }
 
    /**
     * Interface ArrayAccess
     * @param mixed $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->vars);
    }
 
    /**
     * Interface ArrayAccess
     *
     * Return escaped value for
     *     - scalars
     *     - array (escape keys and values)
     *     - stringifyable instance (class implementing __toString() method)
     *
     * If object: return the object
     *
     * @param mixed $offset
     * @return mixed|null
     */
    public function offsetGet($offset)
    {
        if (isset($this->vars[$offset])) {
            $v = $this->vars[$offset];
            if (is_array($v) || $this('$is_scalar', $v)) {
                return $this('$hsc', $v);
            } elseif (is_object($v)) {
                return $v;
            }
        }
        return null;
    }
 
    /**
     * Interface ArrayAccess
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        $this->vars[$offset] = $value;
    }
 
    /**
     * Interface ArrayAccess
     * @param mixed $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->vars[$offset]);
    }
 
    /**
     * Define the filepath to the external view file to include
     *
     * Rule R001 : Any space inside a name will be automatically converted to DIRECTORY_SEPARATOR
     *
     * For strings : $parts = 'www user view login.php';
     *  - become "www/user/view/login.php"  if DIRECTORY_SEPARATOR = '/'
     *  - become "www\user\view\login.php"  if DIRECTORY_SEPARATOR = '\'
     *
     * For arrays, same rule (R001) for all values inside : $parts = ['www/user', 'view login.php'];
     *  - become "www/user/view/login.php"  if DIRECTORY_SEPARATOR = '/'
     *  - become "www/user\view\login.php"  if DIRECTORY_SEPARATOR = '\'
     *
     * File inclusion remove the inline code
     *
     * @param mixed $parts string|array
     */
    public function setFile($parts)
    {
        $file  = [];
        $parts = is_string($parts) ? explode(' ', $parts) : $parts;
        foreach ($parts as $p) {
            $file[] = str_replace(' ', DIRECTORY_SEPARATOR, $p);
        }
        $this->file = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, $file));
        $this->code = '';
    }
 
    /**
     * Instead on including an external file, use inline code for the view
     *
     * CAREFUL : when you use inline code with dynamic values from the array $vars, you must
     * be absolutely sure that the values are already defined before, otherwise you will only have empty strings
     *
     * Inline code remove the included file
     *
     * @param string $code
     */
    public function setCode(string $code)
    {
        $this->code = $code;
        $this->file = '';
    }
 
    /**
     * This function call a helper defined elsewhere or dynamically
     * Auto-escape if necessary
     *
     * @param string $helper
     * @param array  $args
     * @return mixed
     */
    public function __invoke(string $helper, ...$args)
    {
        if ($helper !== '') {
            if (self::isHelper($helper)) {
                if (empty($this->bound_helpers)) {
                    $this->bound_helpers = self::bindHelpersTo($this);
                }
                $escaped = self::isHelperOfType($helper, HELPER_RETURN_ESCAPED_DATA);
                $helpers = $this->bound_helpers + self::$helpers;
                $helper  = $helpers[$helper];
                $result  = $helper(...$args);
                // being in a HTML context: in any case, the returned data should be escaped
                // if you don't want so, use the specific helper '$raw'
                if ($escaped) {
                    return $result;
                } else {
                    return $this('$hsc', $result);
                }
            }
        }
        return null;
    }
 
    /**
     * @param $name
     * @param $arguments
     */
    public function __call($name, $arguments)
    {
        if (self::isHelper($name)) {
            return $this->__invoke($name, ...$arguments);
        } elseif (self::isHelper('$'.$name)) {
            return $this->__invoke('$'.$name, ...$arguments);
        } else {
            return null;
        }
    }
 
    /**
     * Magic method that returns a string instead of current instance of the class in a string context
     */
    public function __toString()
    {
        if (($this->file !== '') && is_file($this->file)) {
            ob_start();
            include $this->file;
            return ob_get_clean();
        } else {
            return $this->code;
        }
    }
 
    //region HELPER ZONE
    /**
     * @var array  [name => closure]
     */
    private static $helpers = [];
    /**
     * @var array  [path to the helpers file to include]
     */
    private static $helpers_file_path = [];
    /**
     * @var array [helper's name => [type]]
     */
    private static $helpers_types = [];
    /**
     * @var array   [helpers filepath to inject]
     */
    private static $helpers_file_to_inject = [];
 
    /**
     * @param string   $name
     * @param \Closure $closure
     * @param int      ...$types  HELPER_RETURN_ESCAPED_DATA HELPER_BOUND_TO_CLASS_INSTANCE
     */
    public static function addHelper(string $name, \Closure $closure, int ...$types)
    {
        self::$helpers[$name] = $closure;
        foreach ($types as $t) {
            self::$helpers_types[$name][] = $t; // HELPER_BOUND_TO_CLASS_INSTANCE HELPER_RETURN_ESCAPED_DATA
        }
    }
 
    /**
     * @param array $helpers [name => Closure | name => [Closure, ...type]]
     */
    public static function addHelpers(array $helpers)
    {
        foreach ($helpers as $name => $h) {
            if ($h instanceof \Closure) {
                self::$helpers[$name] = $h;
            } elseif (is_array($h)) {
                self::addHelper($name, array_shift($h), ...$h);
            }
        }
    }
 
    /**
     * @return array [name => closure]
     */
    public static function helpers(): array
    {
        return self::$helpers;
    }
 
    /**
     * Path to the file that contains helpers closure definition
     * The helpers are common to all instances and will be included only once
     *
     * @param string ...$path
     */
    public static function addPathToHelperFile(string ...$path)
    {
        foreach ($path as $p) {
            if ( ! isset(self::$helpers_file_path[$p])) {
                self::$helpers_file_path[$p]    = true;
                self::$helpers_file_to_inject[] = $p;
            }
        }
    }
 
    /**
     * Read the paths and inject only once all the helpers
     */
    public static function injectHelpers()
    {
        foreach (self::$helpers_file_to_inject as $path) {
            if (is_file($path)) {
                self::addHelpers(include $path);
            }
        }
        self::$helpers_file_to_inject = [];
    }
 
    /**
     * @param  string   $helper_name
     * @return array    [int]
     */
    public static function getHelperTypes(string $helper_name): array
    {
        return self::$helpers_types[$helper_name] ?? [];
    }
 
    /**
     * @param  string $helper_name
     * @return bool
     */
    public static function isHelper(string $helper_name): bool
    {
        if (isset(self::$helpers[$helper_name])) {
            return true;
        } else {
            self::injectHelpers();
            return isset(self::$helpers[$helper_name]);
        }
    }
 
    /**
     * Check if the helper has the defined type
     *
     * @param  string $helper_name
     * @param  int    $type
     * @return bool
     */
    public static function isHelperOfType(string $helper_name, int $type): bool
    {
        return isset(self::$helpers_types[$helper_name])
            ? in_array($type, self::$helpers_types[$helper_name])
            : false;
    }
 
    /**
     * @param  array $type      array of types [type]
     * @param  bool  $strict    when match, check if the helper has only the asked types
     * @return array            [helper's name => closure]
     */
    public static function getHelpersByType(array $type, bool $strict = false): array
    {
        $data = [];
        foreach (self::$helpers_types as $name => $v) {
            $intersect = array_intersect($type, $v);
            if (( ! empty($intersect)) && (count($type) === count($intersect))) {
                if ($strict) {
                    if  (count($type) === count($v)) {
                        $data[$name] = self::$helpers[$name];
                    }
                } else {
                    $data[$name] = self::$helpers[$name];
                }
            }
        }
        return $data;
    }
 
    /**
     * Change the helper's binding context to the given one in parameter
     * Only for helpers bound to a class instance
     *
     * @param object $p
     * @return array        [helper's id => bound closure]
     */
    public static function bindHelpersTo(object $p): array
    {
        $helpers = [];
        foreach (self::getHelpersByType([HELPER_BOUND_TO_CLASS_INSTANCE], false) as $name => $hlp) {
            $helpers[$name] = $hlp->bindTo($p, $p);
        }
        return $helpers;
    }
    //endregion
}
 
// make the class directly available on the global namespace
class_alias('rawsrc\PhpEcho\PhpEcho', 'PhpEcho', false);

4 - CODE DU FICHIER AVEC LES HELPERS DE BASE : stdHelpers.php
Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
 
declare(strict_types=1);
 
$helpers = [];
 
/**
 * Return the raw value from the key in parameter
 * CAREFUL : THIS VALUE IS NOT ESCAPED
 *
 * This helper is linked to an instance of PhpEcho
 *
 * @param string $key
 * @return mixed|null
 */
$raw = function(string $key) {
    return $this->vars[$key] ?? null;
};
$helpers['$raw'] = [$raw, HELPER_BOUND_TO_CLASS_INSTANCE, HELPER_RETURN_ESCAPED_DATA];
 
 
/**
 * This is a standalone helper
 *
 * @param $p
 * @return bool
 */
$is_scalar = function($p): bool {
    return is_scalar($p) || (is_object($p) && method_exists($p, '__toString'));
};
$helpers['$is_scalar'] = [$is_scalar, HELPER_RETURN_ESCAPED_DATA];
$helpers['isScalar']   = $helpers['$is_scalar']; // alias for method call
 
 
/**
 * Return an array of escaped values with htmlspecialchars(ENT_QUOTES, 'utf-8') for both keys and values
 * Works for scalar and array type and transform any object having __toString() function implemented to a escaped string
 * Otherwise, keep the object as it
 *
 * This is a standalone helper that is not directly accessible
 * Use instead the common helper '$hsc' which is compatible with arrays
 *
 * @param  array $part
 * @return array
 */
$hsc_array = function(array $part) use (&$hsc_array, $is_scalar): array {
    $data = [];
    foreach ($part as $k => $v) {
        $sk = htmlspecialchars((string)$k, ENT_QUOTES, 'utf-8');
        if (is_array($v)) {
            $data[$sk] = $hsc_array($v);
        } elseif ($is_scalar($v)) {
            $data[$sk] = htmlspecialchars((string)$v, ENT_QUOTES, 'utf-8');
        } else {
            $data[$sk] = $v;
        }
    }
    return $data;
};
 
 
/**
 * This is a standalone helper
 *
 * @param  $p
 * @return mixed
 */
$hsc = function($p) use ($hsc_array, $is_scalar) {
    if ($is_scalar($p)) {
        return htmlspecialchars((string)$p, ENT_QUOTES, 'utf-8');
    } elseif (is_array($p)) {
        return $hsc_array($p);
    } else {
        return '';
    }
};
$helpers['$hsc'] = [$hsc, HELPER_RETURN_ESCAPED_DATA];
 
 
/**
 * Return the html attribute "selected" if $p == $ref
 * This is a standalone helper
 *
 * @param $p        value to check
 * @param $ref      selected value ref
 * @return string
 */
$selected = function($p, $ref) use ($is_scalar): string {
    return $is_scalar($p) && $is_scalar($ref) && ((string)$p === (string)$ref) ? ' selected ' : '';
};
$helpers['$selected'] = [$selected, HELPER_RETURN_ESCAPED_DATA];
 
 
/**
 * Return the html attribute "checked" if $p == $ref
 * This is a standalone helper
 *
 * @param $p        value to check
 * @param $ref      checked value ref
 * @return string
 */
$checked = function($p, $ref) use ($is_scalar): string {
    return $is_scalar($p) && $is_scalar($ref) && ((string)$p === (string)$ref) ? ' checked ' : '';
};
$helpers['$checked'] = [$checked, HELPER_RETURN_ESCAPED_DATA];
 
 
// return the array of helpers to PhpEcho
return $helpers;

5 - CONCLUSION

J'espère qu'avec cette évolution majeur de PhpEcho, il vous sera possible dorénavant de produire plus facilement vos codes web.
Si vous codez des helpers sympas, n'hésitez pas à les partager avec les membres de DVP.

Juste pour finir, voici la version du tuto du précédent billet compatible avec PhpEcho v.2.0.0 : Layout.php
Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <?= implode('', $this('$raw', 'meta') ?? []) ?>
    <title><?= $this['title'] ?></title>
</head>
<body>
<?= $this('$raw', 'body') ?>
</body>
</html>
à comparer avec la version compatible PhpEcho v.1.0.0
Code php : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <?= implode('', $this['meta'] ?? []) ?>
    <title><?= $this('title') ?></title>
</head>
<body>
<?= $this['body'] ?>
</body>
</html>

Bon code à tous

rawsrc

Envoyer le billet « PhpEcho Version 2.0.0 » dans le blog Viadeo Envoyer le billet « PhpEcho Version 2.0.0 » dans le blog Twitter Envoyer le billet « PhpEcho Version 2.0.0 » dans le blog Google Envoyer le billet « PhpEcho Version 2.0.0 » dans le blog Facebook Envoyer le billet « PhpEcho Version 2.0.0 » dans le blog Digg Envoyer le billet « PhpEcho Version 2.0.0 » dans le blog Delicious Envoyer le billet « PhpEcho Version 2.0.0 » dans le blog MySpace Envoyer le billet « PhpEcho Version 2.0.0 » dans le blog Yahoo

Mis à jour 12/04/2020 à 09h11 par rawsrc

Catégories
HTML / CSS , PHP , Développement Web

Commentaires

  1. Avatar de rawsrc
    • |
    • permalink
    Bonjour,

    suite à des tests d'optimisation beaucoup plus poussés (montée de charge en particulier), j'ai constaté l'exécution d'un code redondant sur la liaison des helpers à l'instance de la classe courante.
    Redondance supprimée via un mécanisme de gestion de liaison des helpers.

    Mise à jour du code publiée dans ce billet et sur GitHub.
    Comme c'est une optimisation interne au fonctionnement de la classe, il n'y a aucun impact en terme de code externe sur l'utilisation de cette classe.
    Mis à jour 06/04/2020 à 10h18 par rawsrc
  2. Avatar de laurentSc
    • |
    • permalink
    Bonjour,
    je tente d'utiliser cette nouvelle version. Tu m'as dit qu'il y a une nouvelle syntaxe (avec addChild). J'ai essayé d'adapter l'exemple d'utilisation de la version 1 avec cette syntaxe, mais c'est pas bon. De plus, dans ton billet, cette syntaxe n'est pas évoquée. Et mon essai n'est pas bon. Pourrais-tu le corriger ? (et compléter ton billet) :

    login.php :

    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    $page = new PhpEcho([DIR_ROOT, 'view Layout.php']);
    $page->addChild('body', [DIR_ROOT, 'view LoginForm.php'], [
        'url_submit' => '/index.php?page=loginsubmit',
        'login'      => 'rawsrc'
    ]);
    echo $page;

    j'ai aussi modifié loginform.php :

    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <p>Veuillez vous identifier</p>
    <form method=post action="<?= URL_HOME.$this['url_submit'] ?>">
        <label>Identifiant</label>
        <input type="text" name="login" value="<?= $this['login'] ?>"><br>
        <label>Mot de passe</label>
        <input type="password" name="pwd" value=""><br>
        <input type="submit" name="submit" value="SE CONNECTER">
    </form>
    <br>
    <p style="display:<?= $this['show_error'] ?? 'none' ?>"><strong><?= $this['err_msg'] ?></strong></p>
    plus de notation appel de fonction.
    Visiblement, le tableau passé ligne 3 et 4 de login.php n'est pas attendu. Comment faire ? (J'ai bien pris la version sur GitHub)