{"id":231596,"date":"2022-12-20T12:55:00","date_gmt":"2022-12-20T09:55:00","guid":{"rendered":"https:\/\/wordpress.mediadoma.com\/?p=231596"},"modified":"2022-12-20T12:55:10","modified_gmt":"2022-12-20T09:55:10","slug":"widget-wordpress-refactoring-parte-10","status":"publish","type":"post","link":"https:\/\/wordpress.mediadoma.com\/it\/widget-wordpress-refactoring-parte-10\/","title":{"rendered":"Widget WordPress: refactoring, parte 10"},"content":{"rendered":"\n<p>Per quanto riguarda il refactoring di WordPress Widget Boilerplate, siamo a buon punto. \u00c8 stato fatto molto lavoro in modo tale che l&#8217;introduzione di nuove classi, funzionalit\u00e0 e funzionalit\u00e0 dovrebbe essere molto pi\u00f9 semplice.<\/p>\n<p>E non solo: dovrebbe essere pi\u00f9 facile da seguire.<\/p>\n<p><a href=\"https:\/\/wordpress.mediadoma.com\/it\/widget-wordpress-refactoring-parte-9\/\" title=\"Grazie al lavoro nell'ultimo post\">Grazie al lavoro nell&#8217;ultimo post<\/a>, abbiamo molto lavoro su cui costruire, vale a dire un&#8217;interfaccia amministrativa di base.<\/p>\n<p>Infine, l&#8217;ultimo post diceva:<\/p>\n<blockquote>\n<p>Nei prossimi articoli, questo continuer\u00e0 ad evolversi ma, come puoi vedere, ci stiamo assicurando di avere un&#8217;unica classe base di funzionalit\u00e0 per parlare con WordPress e una classe specifica per il rendering del modulo amministrativo.<\/p>\n<\/blockquote>\n<p>Ed \u00e8 qui che riprenderemo in questo articolo. In particolare, esamineremo la sanificazione e la serializzazione dei dati, nonch\u00e9 il recupero dei dati salvati nel widget.<\/p>\n<h2>The WordPress Widget Boilerplate: Refactoring Parte 10<\/h2>\n<h3>Refactoring dell&#8217;interfaccia utente<\/h3>\n<p>Prima di entrare nella serializzazione, c&#8217;\u00e8 del lavoro minore che dovremo fare per la nostra vista amministrativa. Ricordiamo dai post precedenti della serie che abbiamo creato un modulo che accetta:<\/p>\n<ul>\n<li>un titolo,<\/li>\n<li>alcuni contenuti,<\/li>\n<li>e una casella di controllo.<\/li>\n<\/ul>\n<p>Questo viene visualizzato bene, ma esclude alcune funzionalit\u00e0 chiave <a href=\"https:\/\/codex.wordpress.org\/Widgets_API#Widgets_API\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">dell&#8217;API dei widget<\/a>. Vale a dire, dobbiamo assicurarci di denominare correttamente i nostri elementi utilizzando le seguenti funzioni:<\/p>\n<ul>\n<li><a href=\"https:\/\/developer.wordpress.org\/reference\/classes\/wp_widget\/get_field_id\/\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">get_field_id<\/a><\/li>\n<li><a href=\"https:\/\/developer.wordpress.org\/reference\/classes\/wp_widget\/get_field_name\/\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">get_field_name<\/a><\/li>\n<\/ul>\n<p>E poi scriveremo la nostra funzione chiamata semplicemente <a href=\"https:\/\/codex.wordpress.org\/Widgets_API#Widgets_API\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">get<\/a> che spiegher\u00f2 momentaneamente.<\/p>\n<p>Le funzioni di cui sopra sono necessarie perch\u00e9 aiutano WordPress a tenere traccia di quante istanze del widget vengono utilizzate e quale l&#8217;utente sta modificando. In altre parole, otteniamo molte funzionalit\u00e0 gratuitamente.<\/p>\n<p>Prima di mostrarti il \u200b\u200bcodice, voglio discutere brevemente lo scopo della\u00a0 funzione <strong>get<\/strong> che stiamo per introdurre. In breve, \u00e8 un modo per passare una chiave (come nella chiave in una coppia chiave\/valore) in una funzione e quindi far s\u00ec che recuperi facilmente un valore per noi in modo che mantenga la nostra interfaccia il pi\u00f9 pulita possibile.<\/p>\n<p>Quindi, per prima cosa, <a href=\"https:\/\/gist.github.com\/tommcfarlin\/392a2eda9ebc0b0a59cd4b364e427445#file-00-get-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">il metodo get<\/a> :<\/p>\n<pre><code>&lt;?php\n\n\/**\n * If the value for the key exists in the current instance of the widget, then it will\n * retrieve it. Otherwise, it will return an empty value.\n *\n * @param string $key the used to identify the value of the widget.\n * @param array $instance the options for the instance of this widget\n *\/\nprotected function get($key, $instance)\n{\n    return empty($instance[$key])? '': $instance[$key];\n}<\/code><\/pre>\n<p>La cosa importante da notare \u00e8 che questo metodo accetta non solo la chiave per il valore che stiamo leggendo, ma un array che fa riferimento all&#8217;istanza dell&#8217;array.<\/p>\n<p><a href=\"https:\/\/gist.github.com\/tommcfarlin\/392a2eda9ebc0b0a59cd4b364e427445#file-01-admin-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">E ora, l&#8217;interfaccia utente modificata<\/a> :<\/p>\n<pre><code>&lt;?php\n\/*\n * This file is part of WordPress Widget Boilerplate\n * (c) Tom McFarlin &lt;tom@tommcfarlin.com&gt;\n *\n * This source file is subject to the GPL license that is bundled\n * with this source code in the file LICENSE.\n *\/\n?&gt;\n\n&lt;div class=\"widget-content\"&gt;\n    &lt;p&gt;\n        &lt;input\n            type=\"text\"\n            id=\"&lt;?php echo esc_attr($this-&gt;get_field_id('title')); ?&gt;\"\n            name=\"&lt;?php echo esc_attr($this-&gt;get_field_name('title')); ?&gt;\"\n            value=\"&lt;?php echo $this-&gt;get('title', $instance) ?&gt;\"\n            placeholder=\"Widget Title\"\n            class=\"widefat\"\n        \/&gt;\n    &lt;\/p&gt;\n\n    &lt;p&gt;\n        &lt;textarea\n            id=\"&lt;?php echo esc_attr($this-&gt;get_field_id('content')); ?&gt;\"\n            name=\"&lt;?php echo esc_attr($this-&gt;get_field_name('content')); ?&gt;\"\n            placeholder=\"Widget Content\"\n            style=\"width:100%;\"&gt;&lt;?php echo $this-&gt;get('content', $instance) ?&gt;&lt;\/textarea&gt;\n    &lt;\/p&gt;\n\n    &lt;p&gt;\n        &lt;input\n            type=\"checkbox\"\n            value=\"on\"\n            name=\"&lt;?php echo esc_attr($this-&gt;get_field_name('display-title')); ?&gt;\"\n            id=\"&lt;?php echo esc_attr($this-&gt;get_field_id('display-title')); ?&gt;\"\n            &lt;?php checked('on', $this-&gt;get('display-title', $instance), true); ?&gt;\n            class=\"checkbox\"\n        \/&gt;\n        &lt;label for=\"&lt;?php echo esc_attr($this-&gt;get_field_id('display-title')); ?&gt;\"&gt;Display Title?&lt;\/label&gt;\n    &lt;\/p&gt;\n&lt;\/div&gt;&lt;!-- .widget-content --&gt;\n<\/code><\/pre>\n<p>Ma questo lascia ancora la funzionalit\u00e0 carente e lascia il lavoro da fare per noi. Vale a dire, dobbiamo disinfettare i dati e ritrasmetterli a WordPress, in modo che salvi i dati.<\/p>\n<h3>Sanificazione e serializzazione<\/h3>\n<p>Ai fini del nostro esempio, saremo molto severi in ci\u00f2 che permettiamo. Vale a dire, supporteremo solo il testo di base e elimineremo tutto in modo aggressivo.<\/p>\n<p>Ci\u00f2 significa che non consentiremo markup o cose del genere. Invece, rimuoveremo tutto ci\u00f2 che non \u00e8 testo di base. Possiamo decorarlo un po&#8217; quando arriva il momento di mostrarlo sul front-end, ma lo lasceremo fino al post appropriato.<\/p>\n<p>Per fare ci\u00f2, utilizzeremo le seguenti funzioni:<\/p>\n<ul>\n<li><a href=\"https:\/\/php.net\/manual\/en\/function.strip-tags.php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">strip_tags<\/a><\/li>\n<li><a href=\"https:\/\/php.net\/manual\/en\/function.stripslashes.php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">strisce<\/a><\/li>\n<\/ul>\n<p>Ricordiamo che abbiamo due campi nel nostro widget: il campo del titolo e il campo del contenuto. A seconda del tipo di widget che stai creando, potresti aver bisogno di una sola classe o funzione per disinfettare i dati. In altre situazioni, potresti aver bisogno di qualcosa di pi\u00f9 complesso.<\/p>\n<p>Tienilo a mente mentre esaminiamo questo codice poich\u00e9 questa non sar\u00e0 una soluzione valida per tutti. Invece, sar\u00e0 specifico per questo.<\/p>\n<p>Ad ogni modo, per sanificare i dati, scriveremo una classe specifica per questo scopo, e poi la metteremo a disposizione della nostra classe WidgetAdmin.<\/p>\n<p><a href=\"https:\/\/gist.github.com\/tommcfarlin\/392a2eda9ebc0b0a59cd4b364e427445#file-02-widget-serializer-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">Ecco la classe nella sua interezza<\/a> con una descrizione da seguire:<\/p>\n<pre><code>&lt;?php\n\n\/*\n * This file is part of WordPress Widget Boilerplate\n * (c) Tom McFarlin &lt;tom@tommcfarlin.com&gt;\n *\n * This source file is subject to the GPL license that is bundled\n * with this source code in the file LICENSE.\n *\/\n\nnamespace WordPressWidgetBoilerplateWordPress;\n\n\/**\n * Santiizes and saves the data for the widget.\n *\/\nclass WidgetSerializer\n{\n    \/**\n     * Updates the values of the widget. Sanitizes the information before saving it.\n     *\n     * @param array $newInstance the array of new options to save\n     *\/\n    public function update($newInstance)\n    {\n        $instance = [];\n        foreach ($newInstance as $key =&gt; $value) {\n            $instance[$key] = strip_tags(\n                stripslashes($value)\n            );\n        }\n\n        return $instance;\n    }\n}\n<\/code><\/pre>\n<p>La classe dovrebbe essere diretta. Accetta i valori in entrata del widget, li disinfetta e quindi restituisce un nuovo array da restituire a WordPress.<\/p>\n<p>C&#8217;\u00e8 un problema per\u00f2. Questa classe deve essere una propriet\u00e0 della\u00a0 classe <strong>Widget<\/strong> principale \u00a0mostrata nell&#8217;ultimo post.<\/p>\n<p>In secondo luogo, il\u00a0 metodo di <strong>aggiornamento<\/strong> che fa parte dell&#8217;API Widgets \u00e8 ci\u00f2 che chiamer\u00e0 in questa classe. Non \u00e8 necessario passare la variabile <strong>$oldInstance<\/strong> nel serializzatore ma \u00e8 necessaria per il metodo di aggiornamento.<\/p>\n<p>Ecco la classe <strong>Widget<\/strong> <a href=\"https:\/\/gist.github.com\/tommcfarlin\/392a2eda9ebc0b0a59cd4b364e427445#file-03-widget-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">come \u00e8 attualmente costruita<\/a> :<\/p>\n<pre><code>&lt;?php\n\n\/*\n * This file is part of WordPress Widget Boilerplate\n * (c) Tom McFarlin &lt;tom@tommcfarlin.com&gt;\n *\n * This source file is subject to the GPL license that is bundled\n * with this source code in the file LICENSE.\n *\/\n\nnamespace WordPressWidgetBoilerplateWordPress;\n\nuse WP_Widget;\n\nclass Widget extends WP_Widget\n{\n    \/**\n     * @var string unique identifier for your widget\n     *\/\n    protected $widgetSlug;\n\n    \/**\n     * Initializes the plugin by setting its properties and calling the parent class with the description.\n     *\n     * @param string           $widgetSlug       unique identifier for your widget\n     * @param WidgetSerializer $widgetSerializer the class responsible for saving widget options\n     *\/\n    public function __construct($widgetSlug)\n    {\n        $this-&gt;widgetSlug = $widgetSlug;\n\n        parent::__construct(\n            $this-&gt;getWidgetSlug(),\n            __('Widget Name', $this-&gt;getWidgetSlug()),\n            [\n                'classname' =&gt; $this-&gt;getWidgetSlug().'-class',\n                'description' =&gt; __('Short description of the widget goes here.', $this-&gt;getWidgetSlug()),\n            ]\n        );\n    }\n\n    \/**\n     * Return the widget slug.\n     *\n     * @return string slug variable\n     *\/\n    public function getWidgetSlug()\n    {\n        return $this-&gt;widgetSlug;\n    }\n\n    \/**\n     * Displays the administrative view of the form and includes the options\n     * for the instance of the widget as arguments passed into the function.\n     *\n     * @param array $instance the options for the instance of this widget\n     *\/\n    public function form($instance)\n    {\n        include plugin_dir_path(__FILE__).'Views\/Admin.php';\n    }\n\n    \/**\n     * Updates the values of the widget. Uses the serialization class to sanitize the\n     * information before saving it.\n     *\n     * @param array $newInstance the values to be sanitized and saved\n     * @param array $oldInstance the values that were originally saved\n     *\/\n    public function update($newInstance, $oldInstance)\n    {\n        return $this-&gt;widgetSerializer-&gt;update($newInstance, $oldInstance);\n    }\n\n    \/**\n     * If the value for the key exists in the current instance of the widget, then it will\n     * retrieve it. Otherwise, it will return an empty value.\n     *\n     * @param string $key      the used to identify the value of the widget\n     * @param array  $instance the options for the instance of this widget\n     *\/\n    protected function get($key, $instance)\n    {\n        return empty($instance[$key])? '': $instance[$key];\n    }\n}\n<\/code><\/pre>\n<p>Ma se aggiorni la pagina, potresti notare che la sanificazione e la serializzazione non sembrano funzionare durante il recupero dei dati. Ed \u00e8 quello che esamineremo nel prossimo post.<\/p>\n<h2>Recupero dati<\/h2>\n<p>Si noti che sebbene la funzionalit\u00e0 sembri incompleta per questo (poich\u00e9 i dati non sterilizzati sono ancora visualizzati), ci concentriamo sull&#8217;assicurarci di scrivere classi con coesione, responsabilit\u00e0 e che non siano strettamente accoppiate.<\/p>\n<p>Ci accingiamo ad iterare un po&#8217; di pi\u00f9 su questo nel prossimo post. Quindi studia il codice sopra, implementalo se \u00e8 quello che hai fatto, e partiremo da l\u00ec nel prossimo post.<\/p>\n<p><div id=\"PostUnique_PostSource\" style=\"padding-top: 50px\">Fonte di registrazione:  <a target=\"_blank\" rel=\"noopener nofollow\" href=\"\/\/tommcfarlin.com\" class=\"external external_icon\">tommcfarlin.com<\/a><\/div><\/p>\n","protected":false},"excerpt":{"rendered":"<p>E ora, iniziamo ad aggiungere funzionalit\u00e0 di sanificazione e serializzazione in WordPress Widget Boilerplate.<\/p>\n","protected":false},"author":1,"featured_media":234961,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_wp_rev_ctl_limit":""},"categories":[720,844],"tags":[1168],"class_list":["post-231596","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-sviluppatore","category-tutorial","tag-affiai-it"],"_links":{"self":[{"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/posts\/231596","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/comments?post=231596"}],"version-history":[{"count":0,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/posts\/231596\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/media\/234961"}],"wp:attachment":[{"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/media?parent=231596"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/categories?post=231596"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/tags?post=231596"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}