toast
toast

Reputation: 1980

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

Upvotes: 3

Views: 1690

Answers (2)

Mohammad_Hosseini
Mohammad_Hosseini

Reputation: 2599

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');

Upvotes: 2

rob006
rob006

Reputation: 22174

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.

Upvotes: 0

Related Questions