A search in this forum and on the web shows there are several ways to use third party code in a plugin. There seems to be no "that's the way to do it" and though in theory it is simple in practice it's not very straightforward. Not for me anyway.
So in theory these are the steps to use a third party library in a plugin:
- in the command line go to the root of your plugin
- let composer install the desired library
- add the library to the plugin by using the
usekeyword - use the
newkeyword to create an object from the third party class
Using Grav version 1.7.41.1 I created a new plugin by following the instructions in Step 2 - Create Randomizer plugin
Then from within the new plugin's root dir I did composer require josantonius/language-code followed by a composer update (not sure whether the second command is needed).
The library is added in the vendor directory and all is well up to this point.
In the main (and only) plugin PHP file I Include the third party library by adding use Josantonius\LanguageCode\LanguageCode;
Finally as a test I try to use the third party code like this:
public function onPluginsInitialized(): void
{
// Don't proceed if we are in the admin plugin
if ($this->isAdmin()) {
return;
}
$languageCode = new LanguageCode();
dump($languageCode->getName('en'));
// Enable the main events we are interested in
$this->enable([
// Put your main events here
]);
}
VSC indicates a problem by underlining "LanguageCode" in red and reports: "Undefined type 'Josantonius\LanguageCode\LanguageCode'".
What am I missing here?