Minggu, 02 September 2018

GitHub autoload.php

Some of you may need autoload.php after downloading a PHP library from gitHub. This post may be helpfull.

Here is how autoload.php looks like:

<?php
/**
 * Users who do not have 'composer' to manage dependencies, include this
 * file to provide auto-loading of the classes in this library. 
 */
spl_autoload_register ( function ($class) {
 /*
  * PSR-4 autoloader, based on PHP Framework Interop Group snippet (Under MIT License.)
  * https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
  */
 $prefix = "Project\";
 $base_dir = __DIR__ . "/src/";
 
 /* Only continue for classes in this namespace */
 $len = strlen ( $prefix );
 if (strncmp ( $prefix, $class, $len ) !== 0) {
  return;
 }
 
 /* Require the file if it exists */
 $relative_class = substr ( $class, $len );
 $file = $base_dir . str_replace ( '\\', '/', $relative_class ) . '.php';
 if (file_exists ( $file )) {
  require $file;
 }
} );
?>

I'd like you to take a look at the '$prefix = "Project\\";'.  What you have to do is just change the "Project" with the prefix used referring to $base_dir directory. The easiest way to find out is by opening the example.

For example, I was using Mike42 library to print to POS printer. Here is just a part of the example code:

<?php
/* Example print-outs using the older bit image print command */
require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;

$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);

In Mike42's case, the autoload.php will be:

<?php
/**
 * Users who do not have 'composer' to manage dependencies, include this
 * file to provide auto-loading of the classes in this library. 
 */
spl_autoload_register ( function ($class) {
 /*
  * PSR-4 autoloader, based on PHP Framework Interop Group snippet (Under MIT License.)
  * https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
  */
 $prefix = "Mike42\";
 $base_dir = __DIR__ . "/src/Mike42/";
 
 /* Only continue for classes in this namespace */
 $len = strlen ( $prefix );
 if (strncmp ( $prefix, $class, $len ) !== 0) {
  return;
 }
 
 /* Require the file if it exists */
 $relative_class = substr ( $class, $len );
 $file = $base_dir . str_replace ( '\\', '/', $relative_class ) . '.php';
 if (file_exists ( $file )) {
  require $file;
 }
} );
?>

The prefix Mike42 refers to directory /src/Mike42.

I hope this can help you

Tidak ada komentar:

Posting Komentar