✅ WEB- ja WordPress -uutiset, -teemat, -laajennukset. Täällä jaamme vinkkejä ja parhaita verkkosivustoratkaisuja.

Nopea prototyyppi: Prototype to Code, osa 1

19

Mitä tulee nopeisiin prototyyppeihin ja WordPressiin, olemme tähän mennessä tehneet kaksi asiaa:

  1. suunniteltu laajennus ,
  2. piirsi kaavion siitä, kuinka koodi voidaan järjestää

Tässä vaiheessa olemme tehneet tarpeeksi työtä oikeuttaaksemme koodimme uudelleenmuodostamisen. Toisin sanoen aiomme alkaa muuntaa prototyyppiä koodiksi. Mutta tämä on jotain, joka on tehtävä kahdessa vaiheessa.

Ensinnäkin aiomme yksinkertaisesti esitellä luokat, jotka edustavat edellisen viestin kaavioita ja jotka kiteyttävät kunkin projektin vastuun.

Sen jälkeen tarkastellaan koodin järjestämistä nimiavaruuksiin ja paketeihin. Ennen kuin voimme tehdä sen, meidän on kuitenkin varmistettava, että koodi on oliosuuntautunut ja toimii edelleen. Näin siis tässä postauksessa tapahtuu.

Prototyyppi koodiin

Jos olet lukenut aiempia viestejä, huomaa, että aion seurata edellisessä viestissä hahmottelemaani organisaatiota. Sinun ei tietenkään tarvitse noudattaa tätä erityistä mallia.

Sana lähteen hallinnasta

Jos käytät lähdeohjausta, suosittelen tässä tapauksessa luomaan päähaaran haaran (jos käytät Gitiä), jotta voit tehdä työsi ilman koodin vakaan version ankaruutta.

Tämä on hieman sarjan soveltamisalan ulkopuolella, joten jos et käytä lähteen hallintaa, älä huoli. Jos olet, valitsen tämän sivuliikkeen nimen kehittävän . Yhdistän sen takaisin masteriin , kun olen varma, että se toimii.

Koodin kirjoittaminen

Eilen luonnostellun työn mukaisesti aion luoda kaksi luokkaa:

  1. metabox-luokka,
  2. metalaatikon näyttöluokka.

Koodia käytetään jonkin verran uudelleen siitä, mitä olemme jo nähneet, kuten näet seuraavassa koodissa.

Koodi

Ensinnäkin metalaatikkomme :

<?php
/**
 * Registers the Meta Box with WordPress.
 *
 * @author Tom McFarlin
 * @since  0.2.0
 */

/**
 * Registers the Meta Box with WordPress. Defines the ID, title, display function,
 * and the post type on which it will live.
 *
 * @author Tom McFarlin
 * @since  0.2.0
 */
class Meta_Box {

    /**
     * A reference to the class that will display the contents in the meta box.
     *
     * @access private
     * @var    Meta_Box_Display
     */
    private $meta_box_display;

    /**
     * Instantiates the class by setting its property equal to a reference to its display.
     */
    public function __construct() {
        $this->meta_box_display = new Meta_Box_Display();
    }

    /**
     * The function responsible for hooking into the WordPress API.
     */
    public function init() {

        add_meta_box(
            'three-recent-posts',
            'Three Recent Posts',
            array( $this->meta_box_display, 'display' ),
            'post',
            'side'
        );
    }
}

Ja seuraavaksi meidän näyttömme :

<?php
/**
 * Defines the display for the meta box.
 *
 * @author Tom McFarlin
 * @since  0.2.0
 */

/**
 * Defines the display for the meta box that will render the content in the
 * context of its meta box.
 *
 * @author Tom McFarlin
 * @since  0.2.0
 */
class Meta_Box_Display {

    /**
     * A reference to the class that will display the contents in the meta box.
     *
     * @access private
     * @var    Post_Messenger
     */
    private $messenger;

    /**
     * Instantiates the object by setting a property equal to that of the class
     * responsible for rendering the messages from the post query.
     */
    public function __construct() {
        $this->messenger = new Post_Messenger( $this );
    }

    /**
     * If there are posts to display, renders them in the metabox. Otherwise, displays
     * a note that there are no posts to display.
     */
    public function display( $message) {
        $this->messenger->get_message();
    }
}

Että metaruutukoodissa, metalaatikkokoodissa me eksplisiittisesti instantoimme näytön, jotta voimme tarvittaessa kutsua sitä näyttömenetelmäksi.

Toinen vaihtoehto olisi instantoida nämä kaksi objektia erikseen ja sitten ruiskuttaa näyttö metalaatikkoon konstruktoriinjektiolla tai jollain vastaavalla. Tämä on tehtävä kolmannen osapuolen luokassa.

Tämän edut tulevat siitä, että kaksi luokkaa irrotetaan hieman enemmän. Ehkä käymme läpi, kuinka tämä tehdään seuraavassa postauksessa.

Sen jälkeen meidän on edettävä ja määriteltävä luokka, joka on vastuussa viestien näyttämisestä Meta Box Display -kontekstissa. Tätä kutsumme Post Messengeriksi :

<?php
/**
 * Display content for the meta box when requested.
 *
 * @author Tom McFarlin
 * @since  0.2.0
 */

/**
 * Retrieves information from the class responsible for querying the database and
 * renders it in the context of our meta box when called via the Meta Box Display.
 *
 * @author Tom McFarlin
 * @since  0.2.0
 */
class Post_Messenger {

    /**
     * A reference to the query resonsible for retrieving post information from
     * the database.
     *
     * @access private
     * @var    WP_Query
     */
    private $query;

    /**
     * A reference to the message that's displayed in the view of the
     * meta box.
     *
     * @access private
     */
    private $message;

    /**
     * Instantiates the class by setting a reference to the query.
     */
    public function __construct() {
        $this->query = new Post_Query();
    }

    /**
     * Retrieves the content to be displayed in the meta box.
     */
    public function get_message() {

        $this->get_description();

        if ($this->query->has_posts()) {
            $this->get_post_message();
        } else {
            $this->get_no_posts_message();
        }
    }

    /**
     * Displays the description of the content of the meta box.
     *
     * @access private
     */
    private function get_post_message() {
        include_once 'post-list.php';
    }

    /**
     * Displays the description of the content of the meta box.
     *
     * @access private
     */
    private function get_description() {
        include_once 'message-description.php';
    }

    /**
     * Displays a message of there are no recent posts.
     *
     * @access private
     */
    private function get_no_posts_message() {
        include_once 'no-post-list.php';
    }
}

Huomaa tässä, että Post Messenger viittaa myös viestikyselyyn. Tämä on luokka, jossa tiedonsiirto tietokantaan tapahtuu. Olen myös lisännyt muutaman aputoiminnon yksinkertaistaakseni näkymäkoodia, kuten hetken kuluttua näemme.

<?php
/**
 * Queries the database for three most recent posts.
 *
 * @author Tom McFarlin
 * @since  0.2.0
 */

/**
 * Queries the database for three most recent posts. Returns the query to the
 * caller so that it can be interrogates for posts or not.
 *
 * @author Tom McFarlin
 * @since  0.2.0
 */
class Post_Query {

    /**
     * A reference to the WP_Query this class wraps.
     *
     * @access private
     * @var    WP_Query
     */
    private $query;

    /**
     * Instantiates the class by preparing instance data and executing the
     * query so the display can render the contents.
     */
    public function __construct() {

        $this->query = null;
        $this->get_posts();
    }

    /**
     * Executes the query for returning the post recent posts ordered by date.
     *
     * @access private
     */
    private function get_posts() {

        $args = array(
            'post_type'   => 'post',
            'post_status' => 'publish',
            'orderby'     => 'date',
            'order'       => 'desc',
        );
        $this->query = new WP_Query( $args );

        return $this->query;
    }

    /**
     * A helper function to determine if the query has any posts.
     */
    public function has_posts() {
        return! $this->query->have_posts();
    }

    /**
     * A helper function for retrieving the next post in the list of
     * posts
     */
    public function the_post() {
        return $this->query->the_post();
    }
}

Ja siinä se ydinluokille. Tietysti meidän on vielä puhuttava näkemyksistä.

Katselukerrat

Näkymät vastaavat HTML:n hahmontamisesta metalaatikon yhteydessä. En pidä HTML:n kirjoittamisesta PHP:n yhteydessä (enkä myöskään pidä PHP:n sekoittamisesta HTML:n yhteydessä, mutta tämä on väistämätöntä tässä projektissa).

On olemassa hienoja malliprojekteja, jotka tekevät tämän helpommaksi, mutta poikkean. Joka tapauksessa huomaat, että post-list.php- tiedostossa on viittauksia Post Query -luokan aputoimintoihin. Tämä varmistaa, etten paljasta liikaa ominaisuuksia ja riko Demeterin lakia.

Katsotaanpa ensin tuota tiedostoa, koska se on monimutkaisin :

<ol>
    <?php while ($this->query->has_posts()) {  ?>
        <?php $this->query->the_post(); ?>
        <li>
            <a href="<?php get_the_permalink(); ?>" target="_blank">
                <?php echo get_the_title(); ?>
            </a>
        </li>
    <?php } ?>
</ol>

Se näyttää tavalliselta WordPress-koodilta, mutta muista, että koska tätä tiedostoa kutsutaan Post Messengerissä, se viittaa kyselyyn kyselynä, jonka tämä luokka käärii.

Kaksi viimeistä tiedostoa ovat melko suoraviivaisia. Yksi niistä tarjoaa kuvauksen :

<p>
    <span class="description">
        Displays up to the three most recent posts.
    </span><!-- .description -->
</p>

Toinen antaa viestin, kun viestejä ei ole :

<p>There are no recent posts.</p>

Muuten perustoiminnot on tehty.

Pluginin käynnistys

Viimeinen asia, joka meidän on tehtävä, on käynnistää laajennus. Tätä varten muutamme päälaajennustiedoston koodia siten, että se näyttää tältä :

<?php
/**
 * Three Recent Posts
 *
 * @package     TRP
 * @author      Tom McFarlin
 * @copyright   2017 Tom McFarlin
 * @license     MIT
 *
 * @wordpress-plugin
 * Plugin Name: Three Recent Posts
 * Plugin URI:  https://tommcfarlin.com/three-recent-posts/
 * Description: Displays the three mot recent posts in your post editor screen.
 * Version:     0.2.0
 * Author:      Tom McFarlin
 * Author URI:  https://tommcfarlin.com
 * Text Domain: three-recent-posts
 * License:     GPL
 * License URI: http://www.gnu.org/licenses/gpl-3.0.txt
 */

include 'class-meta-box.php';
include 'class-meta-box-display.php';
include 'class-post-messenger.php';
include 'class-post-query.php';

add_action( 'add_meta_boxes', 'trp_start' );
/**
 * Starts the plugin.
 */
function trp_start() {

    $meta_box = new Meta_Box();
    $meta_box->init();
}

Se kytkeytyy WordPressiin, instantoi laajennuksen ja käynnistää sen sitten. Kun käytät sitä WordPress-asennuksessasi, sen pitäisi näyttää täsmälleen samalta kuin ensimmäisen version aikana.

Ainoa ero on, että meillä on nyt asiat järjestetty luokittain yksittäisten toimintojen sijaan.

Huomautuksia

Ensinnäkin tässä on mahdollisuuksia uudelleenjärjestelyyn, joka vähentäisi irrottamista entisestään (kuten erilaiset riippuvuusruiskeet jne.), mutta tämän sarjan tarkoitus ei ole kattaa sitä.

Sen sijaan on ajatus nähdä monien proseduuritoimintojen kirjoittamia laajennuksia ja sitten jakaa ne käsitteellisempiin luokkiin, jotka kiteyttävät heidän vastuunsa.

Toiseksi, jos tarkastelet projektin tämän version arkistossa olevaa lähdekoodia, huomaat, että esittelin myös composer.jsonin. Tämä on siksi, että voin hyödyntää PHP CodeSnifferiä ja WordPress- koodausstandardeja kirjoittaessani koodia.

Sarjan viimeisessä osassa käymme läpi nimivälit ja järjestämme tiedostot uudelleen. Jos aika sallii, sisällytämme automaattisen latausohjelman, jotta meidän ei tarvitse lisätä tiedostoja manuaalisesti laajennustiedostomme yläosaan.

Lopuksi olen yhdistänyt tämän koodin master-koodiin ja merkinnyt sen 0.2.1:ksi (koska minun piti tehdä pieni hotfix-korjaus), koska se on vielä keskeneräinen.

Sarjan postaukset

  1. Nopea prototyyppien luominen WordPressillä: konseptista laajennukseen
  2. Nopea prototyyppien luominen WordPressillä: konseptianalyysi
  3. Nopea prototyyppi: Prototype to Code, osa 1
  4. Rapid Prototyping: Prototype to Code, osa 2
  5. Rapid Prototyping: Esittelyssä automaattinen lataus

Tämä verkkosivusto käyttää evästeitä parantaakseen käyttökokemustasi. Oletamme, että olet kunnossa, mutta voit halutessasi kieltäytyä. Hyväksyä Lisätietoja