How to Use PHP Libraries and Create autoload Like Drupal

269 Views Asked by At

How can i Create my own vendor/autoload with needed libraries Like Drupal in composer directory (drupal) there many files autoload_psr4.php autoload_real.php and ...

1

There are 1 best solutions below

1
Fran Cano On

You are looking for a dependency manager called composer. Composer takes advantage of PHP's spl_autoload_register, an API that allows your script to dinamically include files when missing classnames are found.

For example:

function appAutoloader($className)
{
    $path = $_SERVER['DOCUMENT_ROOT'] . '/app/v2/class/';

    $file = $path.$className.'.php';
    if (file_exists($file)) require_once $file;
}

spl_autoload_register('appAutoloader');

// now I can call...
new Example();
// and file "/app/v2/class/Example.php" will be required automatically

Composer is a powerful generator for this kind of autoloaders. You can include an external library through Composer, and that library can include other libraries as well. With a simple command, Composer will install every dependency required, in order to let you easily use the library by simply loading the "autoload.php" file.

The usage of composer is not rocket science but there's a learning curve. The best thing you can do to learn is find a library that can be installed through composer and try installing it in an existing project.