简体   繁体   中英

How to autoload PHP namespaces without Composer?

I'm trying to use this library: https://github.com/wunderio/docebo-php

However, its not found in Composer, despite it listing the Composer command on the page.

How can I call this library and create a new instance of the Docebo class as shown in the example?

use Docebo\Docebo;

try {
  $docebo = new Docebo('base_url', 'client_id', 'client_secret', 'username', 'password');
} catch (Exception $e) {
  echo $e->getMessage();
}

I attempted to use this library by cloning the github repo, and creating the following:

docebo-php/src$ cat test.php
<?php
require_once("Docebo/Docebo.php");

use Docebo\Docebo;

try {
  $docebo = new Docebo('base_url', 'client_id', 'client_secret', 'username', 'password');
} catch (Exception $e) {
  echo $e->getMessage();
}
?>

This just results in:

$ php test.php
PHP Fatal error:  Interface 'Docebo\DoceboInterface' not found in /var/www/www/htdocs/docebo-php/src/Docebo/Docebo.php on line 18

You can add custom repository with vcs type and install this library using Composer anyway, even if it is not available at Packagist:

{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/wunderio/docebo-php"
        }
    ],
    "require": {
        "wunder/docebo-php": "dev-master"
    }
}

Composer will clone this repo and fetch metadata from it directly.

Note that vcs type should be less problematic than package type, which has some limitations and should be used only if everything else fails.

It's not clear that are you using any framework or just plain PHP code.

my solution is for plain PHP code:

you can write your own PHP autoloader to include libraries like :

function __autoload($class_name)
{
    //class directories
    $directorys = array(
        '/Controllers/',
        '/Libraries/',
    );

    //for each directory
    $ds = "/"; //Directory Seperator
    $dir = dirname(__FILE__); //Get Current file path
    $windir = "\\"; //Windows Directory Seperator
    $path = str_replace($windir, $ds, $dir);

    foreach($directorys as $directory)
    {
        //see if the file exsists
        if(file_exists( $path . $directory . $class_name . '.php'))
        {
            require_once( $path . $directory . $class_name . '.php');
            //only require the class once, so quit after to save effort (if you got more, then name them something else
            return;
        }
    }
}

Store it as autoload.php in your project root directory, then require it on top of any PHP file you have like:

require_once('autoload.php');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM