Rapid Prototyping: Introduktion av Autoloading
Under de senaste inläggen har jag gått igenom processen att ta en idé från idé till prototyp.
Visst, det finns några saker som du kan ändra (och det finns några saker jag skulle ändra när det gäller att organisera klasser). Men poängen med serien är inte att gå igenom alla de olika objektorienterade teknikerna som kan användas för att skapa en lösning.
Istället handlar det om att ta en prototyp och göra om den till något lite mer professionellt. Det finns fortfarande en sak som vi måste göra, dock.
Just nu inkluderar vi alla våra filer genom kravutlåtanden. Och det här fungerar bra för små filer, men att införa autoloading i kombination med namnutrymmen kan göra applikationen ännu renare.
Och det är vad vi ska göra.
Vi presenterar Autoloading
Minns från ett tidigare inlägg (om du har läst det), att autoladdning är en enkel idé:
Det låter bra, eller hur? Men det finns en varning: Du måste skriva autoloader. PHP kan inte lista ut det på egen hand.
Och det är därför jag är ett fan av att se till att våra namnområden också följer en konsekvent katalogstruktur: Om du analyserar namnområdet och namnet på filen är det relativt enkelt att bygga sökvägen till filen och automatiskt ladda den.
Låter det förvirrande? Låt oss först ta en titt på var vi ska placera autoloadern angående vår katalogstruktur:
Uppdatera sedan din plugins bootstrap-fil så att den bara kräver autoloader-filen.
<?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: 1.0.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
*/
namespace McFarlinTRP;
use McFarlinTRPDisplayMeta_Box;
// Import the autoloader.
include_once 'Includes/autoload.php';
add_action( 'add_meta_boxes', __NAMESPACE__. 'trp_start' );
/**
* Starts the plugin.
*/
function trp_start() {
$meta_box = new Meta_Box( dirname( __FILE__) );
$meta_box->init();
}
Självklart behöver vi autoloadern för att ladda våra filer. I huvudsak fungerar det så här:
- separera komponenterna i det inkommande filnamnet (som katalogsökvägen och filnamnet),
- ersätt eventuella understreck med bindestreck för att se till att filen följer strukturen för klassens filnamn,
- börja bygga det fullt kvalificerade sökvägsnamnet (som är katalogen, filnamnet, etc.),
- iterera genom namnområdet ner till klassnamnet och bygg ett fullständigt kvalificerat namn till filen,
- inkludera det i projektet.
Det är rätt fram, eller hur? Om du följer ett konsekvent namnområde, katalog, klassnamn och filnamnsschema kan du återanvända samma autoloader i alla projekt.
Här är en kopia av en autoloader som jag använder och släpper den i nästan alla projekt jag använder. Du kommer att se att det följer exakt vad som beskrivs ovan:
<?php
/**
* Automatically loads the specified file.
*
* @package McFarlinTFP
*/
namespace McFarlinTFP;
/**
* Automatically loads the specified file.
*
* Examines the fully qualified class name, separates it into components, then creates
* a string that represents where the file is loaded on disk.
*
* @package McFarlinTFP;
*/
spl_autoload_register(function( $filename) {
// First, separate the components of the incoming file.
$file_path = explode( '', $filename );
// Get the last index of the array. This is the class we're loading.
if (isset( $file_path[ count( $file_path) - 1 ])) {
$class_file = strtolower(
$file_path[ count( $file_path) - 1 ]
);
/**
* The classname has an underscore, so we need to replace it
* with a hyphen for the file name.
*/
$class_file = str_ireplace( '_', '-', $class_file );
$class_file = "class-$class_file.php";
}
/**
* Find the fully qualified path to the class file by iterating through the $file_path array.
* We ignore the first index since it's always the top-level package. The last index is always
* the file so we append that at the end.
*/
$fully_qualified_path = trailingslashit(
dirname(
dirname( __FILE__)) );
/**
* We start at the second index of the namespace because our directory
* structure does not include 'McFarlin/TRP'.
*/
for ($i = 2; $i < count( $file_path) - 1; $i++) {
$dir = strtolower( $file_path[ $i ] );
$fully_qualified_path .= trailingslashit( $dir );
}
$fully_qualified_path .= $class_file;
// Now we include the file.
if (file_exists( $fully_qualified_path)) {
include_once( $fully_qualified_path );
}
});
Och med detta är plugin inslagen till version 1.0.0. Du kan kolla in det på GitHub (både bokstavligen och bara för recension). Och förhoppningsvis har detta hjälpt med att gå igenom processen att gå från snabb prototyping till koncept inom konceptet WordPress.
Serie inlägg
- Snabb prototyping med WordPress: från koncept till plugin
- Snabb prototyping med WordPress: konceptanalys
- Rapid Prototyping: Prototype To Code, del 1
- Rapid Prototyping: Prototype To Code, del 2
- Rapid Prototyping: Introduktion av Autoloading