Created
October 14, 2020 03:37
-
-
Save relliv/6d355f2657d772da21e269d51711285f to your computer and use it in GitHub Desktop.
PHP PSR-4 Autoloader Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); | |
/** | |
* Custom PSR-4 autoloader | |
* | |
* @param array $packages: array of packages | |
* @source https://github.com/Wilkins/composer-file-loader | |
*/ | |
function loadPsr4Packages($packages) | |
{ | |
foreach ($packages as $namespace => $classpaths) { | |
if (!is_array($classpaths)) { | |
$classpaths = array($classpaths); | |
} | |
spl_autoload_register(function ($classname) use ($namespace, $classpaths) { | |
// Check if the namespace matches the class we are looking for | |
if (preg_match("#^" . preg_quote($namespace) . "#", $classname)) { | |
// Remove the namespace from the file path since it | |
$classname = str_replace($namespace, "", $classname); | |
$filename = preg_replace("#\\\\#", "/", $classname) . ".php"; | |
foreach ($classpaths as $classpath) { | |
$fullpath = __DIR__ . $classpath . "/$filename"; | |
if (file_exists($fullpath)) { | |
require_once $fullpath; | |
} | |
} | |
} | |
}); | |
} | |
} | |
$myPackages = [ | |
//package namespace => package target folder | |
'Spatie\\SchemaOrg\\' => '/./schema-org-3.1.0/src/' | |
]; | |
loadPsr4Packages($myPackages); | |
use Spatie\SchemaOrg\Schema; | |
$localBusiness = Schema::localBusiness() | |
->name('Spatie') | |
->email('[email protected]') | |
->contactPoint(Schema::contactPoint()->areaServed('Worldwide')); | |
echo $localBusiness->toScript(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment