DeepLcom / deepl-php

Official PHP library for the DeepL language translation API.
MIT License
202 stars 23 forks source link

Autoloading not working #25

Closed grandeljay closed 1 year ago

grandeljay commented 1 year ago

Hello,

I'm guessing this is not directly related to this library but I am experiencing some very strange behaviour and was hoping you could still help me.

I am working on a WordPress plugin with the following code:

<?php
/**
 * [...]
 */

namespace My\Namespace;

define( 'PLUGIN_FILEPATH', __FILE__ );
define( 'DEEPL_API_HOST', 'api-free.deepl.com' );
define( 'DEEPL_API_KEY', '[...]' );

require_once __DIR__ . '/vendor/autoload.php'; // composer's autoloader
require_once __DIR__ . '/src/autoload.php'; // my own autoloader for the plugin

$plugin = new Plugin( PLUGIN_FILEPATH );
$plugin->run();

require_once '/vendor/deeplcom/deepl-php/src/Translator.php'; // Required to avoid error
$translator      = new \Deepl\Translator(DEEPL_API_KEY);
$sourceLanguages = $translator->getSourceLanguages();

Without manually requiring the DeepL class I get the following error:

PHP Fatal error:  Uncaught Error: Class "Deepl\Translator" not found in /path/to/my/plugin/my-plugin.php:36
Stack trace:
#0 /path/to/wordpress/wp-settings.php(453): include_once()
#1 /path/to/wordpress/wp-config.php(96): require_once('C:\\laragon\\www\\...')
#2 /path/to/wordpress/wp-load.php(50): require_once('C:\\laragon\\www\\...')
#3 /path/to/wordpress/wp-admin\admin.php(34): require_once('C:\\laragon\\www\\...')
#4 {main}
  thrown in /path/to/my/plugin/my-plugin.php on line 36

Composer commands I have run in an attempt to fix this:

My composer.json:

{
    "require": {
        "deeplcom/deepl-php": "^1.4"
    }
}

I'm probably making an obvious mistake but can't see what. Please help!

Thanks in advance!

JanEbbing commented 1 year ago

The namespace is DeepL, not Deepl, so $translator = new \Deepl\Translator(DEEPL_API_KEY); should be $translator = new \DeepL\Translator(DEEPL_API_KEY);

grandeljay commented 1 year ago

Omg, I am so sorry 😭

Thank you for responding, I really appreciate it!

JanEbbing commented 1 year ago

All good, we've all been there :)