{"id":231679,"date":"2022-12-21T12:45:00","date_gmt":"2022-12-21T09:45:00","guid":{"rendered":"https:\/\/wordpress.mediadoma.com\/?p=231679"},"modified":"2022-12-07T10:29:46","modified_gmt":"2022-12-07T07:29:46","slug":"widget-wordpress-refactoring-parte-11","status":"publish","type":"post","link":"https:\/\/wordpress.mediadoma.com\/it\/widget-wordpress-refactoring-parte-11\/","title":{"rendered":"Widget WordPress: refactoring, parte 11"},"content":{"rendered":"\n<p>Nel post precedente, abbiamo esaminato molte operazioni di refactoring che hanno separato le preoccupazioni nelle rispettive classi.<\/p>\n<p>In definitiva, questo aiuta a mostrare come possiamo mantenere un alto livello di coesione mentre non solo lavoriamo con le classi in WordPress, ma lo facciamo insieme alle API preesistenti.<\/p>\n<p>Poich\u00e9 gli ultimi post sul refactoring della base di codice sono stati cos\u00ec lunghi, l&#8217;attuale set di post si concentra su piccole modifiche incrementali e quindi post pi\u00f9 brevi e pi\u00f9 mirati.<\/p>\n<p>Come accennato nell&#8217;articolo precedente:<\/p>\n<blockquote>\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<\/blockquote>\n<p>Quindi \u00e8 qui che riprenderemo in questo articolo.<\/p>\n<h2>The WordPress Widget Boilerplate: Refactoring Parte 11<\/h2>\n<p>Prima di scrivere qualsiasi codice, la prima cosa da notare \u00e8 che se si popola una delle aree di contenuto del widget (come il titolo) con qualcosa del <a href=\"https:\/\/gist.github.com\/tommcfarlin\/39038338730b7141a19c3d2f48801dac#file-00-example-title-js\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">genere<\/a> :<\/p>\n<pre><code>&lt;script type=\"text\/javascript\"&gt;This is the Title&lt;\/script&gt;<\/code><\/pre>\n<p>E quindi fare clic su Salva, il contenuto effettivo verr\u00e0 disinfettato e scritto nel database. Puoi vedere che questo \u00e8 vero osservando il valore del widget nel database.<\/p>\n<p>Inoltre, i dati sembrano a posto a prima vista, ma se aggiorni la pagina, viene visualizzato il contenuto non disinfettato. Se accedi a un&#8217;altra pagina, come Menu, e poi torni indietro, il contenuto del widget viene visualizzato ma correttamente disinfettato.<\/p>\n<p>Perch\u00e9, quindi, mostra una cosa nel database e una cosa sul front-end dell&#8217;area di amministrazione durante l&#8217;esecuzione di determinati passaggi?<\/p>\n<p>Questo ha a che fare con la cache del widget e, fortunatamente, siamo in grado di svuotare questa cache a piacimento usando qualsiasi hook vogliamo (ovvero, possiamo iscriverci a qualsiasi evento e quindi svuotare la cache).<\/p>\n<\/p>\n<p>Dal <a href=\"https:\/\/developer.wordpress.org\/reference\/functions\/wp_cache_delete\/\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">codice di riferimento<\/a> :<\/p>\n<blockquote>\n<p>Rimuove il contenuto della cache che corrisponde alla chiave e al gruppo.<\/p>\n<\/blockquote>\n<p>Si noti, tuttavia, che \u00e8 necessario fornire la chiave e un gruppo opzionale. In Boilerplate, abbiamo utilizzato lo slug del widget come chiave e gruppo \u00e8 widget.<\/p>\n<h3>Svuotare la cache<\/h3>\n<p>Poich\u00e9 la funzione pu\u00f2 essere agganciata a qualsiasi evento, possiamo creare un abbonato che possiamo agganciare a qualsiasi evento. Ci\u00f2 significa <a href=\"https:\/\/gist.github.com\/tommcfarlin\/39038338730b7141a19c3d2f48801dac#file-01-delete-widget-cache-subscriber-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">che possiamo creare un abbonato DeleteWidgetCache nel nostro spazio dei nomi degli abbonati:<\/a><\/p>\n<pre><code>&lt;?php\n\n&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 WordPressWidgetBoilerplateSubscriber;\n\n\/**\n * Deletes the cached contents of the widget.\n *\/\nclass DeleteWidgetCacheSubscriber extends AbstractSubscriber\n{\n    \/**\n     * {@inheritdoc}\n     *\/\n    public function __construct(string $hook)\n    {\n        parent::__construct($hook);\n    }\n\n    \/**\n     * Flushes the widget's cache based on the key that's specified in the function arguments.\n     *\/\n    public function load()\n    {\n        \/* Because we're implementing an abstract class, we'll parse arguments from the\n         * func_get_args().\n         *\/\n        $args = func_get_args();\n        if (!$this-&gt;hasValidArguments($args)) {\n            return;\n        }\n\n        \/\/ TODO: More to come...\n    }\n\n    \/**\n     * Verifies that we have valid arguments with which to work.\n     *\n     * @param array $args the array of arguments we are validating\n     *\n     * @return bool true if the arguments are valid; otherwise, false\n     *\/\n    private function hasValidArguments(array $args): bool\n    {\n        \/\/ First, check the initial index of the arguments.\n        if (!isset($args[0])) {\n            return false;\n        }\n\n        \/\/ Next, check the values of the arguments for the widget key and group.\n        $args = $args[0];\n        if (!isset($args[0]) &amp;&amp; !isset($args[1])) {\n            return false;\n        }\n\n        return true;\n    }\n}\n<\/code><\/pre>\n<p>Aggiorneremo quindi <a href=\"https:\/\/gist.github.com\/tommcfarlin\/39038338730b7141a19c3d2f48801dac#file-02-wordpress-widget-plugin-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">il bootstrap<\/a> per aggiungere l&#8217;abbonato al registro e utilizzeremo un hook personalizzato, flush_widget_cache, che utilizzeremo momentaneamente.<\/p>\n<pre><code>&lt;?php\n\/**\n * WordPress Widget Boilerplate\n *\n * The WordPress Widget Boilerplate is an organized, maintainable boilerplate for building\n * widgets using WordPress best practices.\n *\n * @package   WordPressWidgetBoilerplate\n * @author    Your Name &lt;email@example.com&gt;\n * @license   GPL-3.0+\n * @link      http:\/\/example.com\n * @copyright 2018 - 2019 Your Name or Company Name\n *\n * @wordpress-plugin\n * Plugin Name:       WordPress Widget Boilerplate\n * Plugin URI:        https:\/\/github.com\/tommcfarlin\/wordpress-widget-boilerplate\n * Description:       An object-oriented foundation for building WordPress Widgets.\n * Version:           1.0.0\n * Author:            Tom McFarlin\n * Author URI:        https:\/\/tommcfarlin.com\n * Text Domain:       widget-name\n * License:           GPL-3.0+\n * License URI:       http:\/\/www.gnu.org\/licenses\/gpl-3.0.txt\n * Domain Path:       \/lang\n *\/\n\nnamespace WordPressWidgetBoilerplate;\n\nuse WordPressWidgetBoilerplateUtilitiesRegistry;\nuse WordPressWidgetBoilerplatePlugin;\nuse WordPressWidgetBoilerplateSubscriberWidgetSubscriber;\nuse WordPressWidgetBoilerplateSubscriberDeleteWidgetCacheSubscriber;\n\n\/\/ Prevent this file from being called directly.\ndefined('WPINC') || die;\n\n\/\/ Include the autoloader.\nrequire_once __DIR__. '\/vendor\/autoload.php';\n\n\/\/ Setup a filter so we can retrieve the registry throughout the plugin.\n$registry = new Registry();\nadd_filter('wpwBoilerplateRegistry', function() use ($registry) {\n    return $registry;\n});\n\n\/\/ Add subscribers.\n$registry-&gt;add('deleteWidgetCacheSubscriber', new DeleteWidgetCacheSubscriber('flush_widget_cache'));\n\n\/\/ Add the Widget base class to the Registry.\n$registry-&gt;add('widgetSubscriber', new WidgetSubscriber('widgets_init'));\n\n\/\/ Start the machine.\n(new Plugin($registry))-&gt;start();\n<\/code><\/pre>\n<p>Ai fini di Boilerplate, utilizzeremo l&#8217;evento personalizzato ogni volta che viene chiamato il codice di serializzazione del widget.<\/p>\n<p>Innanzitutto, definiremo una\u00a0 chiamata <a href=\"https:\/\/developer.wordpress.org\/reference\/functions\/do_action\/\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">do_action<\/a>, la identificheremo come flush_widget_cache, quindi <a href=\"https:\/\/gist.github.com\/tommcfarlin\/39038338730b7141a19c3d2f48801dac#file-03-widget-serialization-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">passeremo gli argomenti necessari<\/a> all&#8217;evento in modo che l&#8217;abbonato possa leggerli:<\/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     * @var string a reference to the slug of the widget to which the serialier is associated\n     *\/\n    private $widgetSlug;\n\n    \/**\n     * Initializes the class.\n     *\n     * @param string a reference to the slug of the widget to which the serialier is associated\n     *\/\n    public function __construct(string $widgetSlug)\n    {\n        $this-&gt;widgetSlug = $widgetSlug;\n    }\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        do_action('flush_widget_cache', [$this-&gt;widgetSlug, 'widget']);\n\n        return $instance;\n    }\n}\n<\/code><\/pre>\n<p>E poi nell&#8217;abbonato, <a href=\"https:\/\/gist.github.com\/tommcfarlin\/39038338730b7141a19c3d2f48801dac#file-04-delete-widget-cache-subscriber-php\" target=\"_blank\" rel=\"noopener nofollow\" class=\"external external_icon\">svuoteremo la cache<\/a> in base agli argomenti in arrivo:<\/p>\n<pre><code>&lt;?php\n\n&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 WordPressWidgetBoilerplateSubscriber;\n\n\/**\n * Deletes the cached contents of the widget.\n *\/\nclass DeleteWidgetCacheSubscriber extends AbstractSubscriber\n{\n    \/**\n     * {@inheritdoc}\n     *\/\n    public function __construct(string $hook)\n    {\n        parent::__construct($hook);\n    }\n\n    \/**\n     * Flushes the widget's cache based on the key that's specified in the function arguments.\n     *\/\n    public function load()\n    {\n        \/* Because we're implementing an abstract class, we'll parse arguments from the\n         * func_get_args().\n         *\/\n        $args = func_get_args();\n        if (!$this-&gt;hasValidArguments($args)) {\n            return;\n        }\n\n        $args = $args[0];\n        wp_cache_delete($args[0], $args[1]);\n    }\n\n    \/**\n     * Verifies that we have valid arguments with which to work.\n     *\n     * @param array $args the array of arguments we are validating\n     *\n     * @return bool true if the arguments are valid; otherwise, false\n     *\/\n    private function hasValidArguments(array $args): bool\n    {\n        \/\/ First, check the initial index of the arguments.\n        if (!isset($args[0])) {\n            return false;\n        }\n\n        \/\/ Next, check the values of the arguments for the widget key and group.\n        $args = $args[0];\n        if (!isset($args[0]) &amp;&amp; !isset($args[1])) {\n            return false;\n        }\n\n        return true;\n    }\n}\n<\/code><\/pre>\n<p>E questo lo fa.<\/p>\n<h2>Pronto per il front-end<\/h2>\n<p>A questo punto, abbiamo un meccanismo in atto che pu\u00f2 svuotare la cache del widget ogni volta che vogliamo, non solo con un evento personalizzato, ma anche con qualsiasi evento offerto da WordPress.<\/p>\n<p>Questo pu\u00f2 tornare utile se stai usando Boilerplate per qualcosa che utilizzer\u00e0 una query memorizzata nella cache o qualsiasi altro meccanismo di memorizzazione nella cache, se \u00e8 per questo, e vuoi assicurarti che i contenuti siano chiari.<\/p>\n<p>Successivamente, esamineremo il rendering dei contenuti sul front-end. Ci stiamo avvicinando alla fine, del refactoring di Boilerplate, ma c&#8217;\u00e8 solo un po&#8217; di pi\u00f9 da fare prima di essere pronti per unirlo al ramo principale della codebase.<\/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>Perch\u00e9, allora, WordPress mostra una cosa nel database e una cosa nell&#8217;area di amministrazione? Questo ha a che fare con la cache dei widget.<\/p>\n","protected":false},"author":1,"featured_media":235955,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_wp_rev_ctl_limit":""},"categories":[896,835,720],"tags":[1168],"class_list":["post-231679","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-codice","category-guida-per-principianti","category-sviluppatore","tag-affiai-it"],"_links":{"self":[{"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/posts\/231679","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=231679"}],"version-history":[{"count":0,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/posts\/231679\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/media\/235955"}],"wp:attachment":[{"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/media?parent=231679"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/categories?post=231679"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wordpress.mediadoma.com\/it\/wp-json\/wp\/v2\/tags?post=231679"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}