I installed PostHog in my PHP codebase, and trying to use it by following the tutorial in this link (https://posthog.com/docs/integrate/server/php
).
I am attempting to call PostHog::init function as a following:
PostHog::init($apikey,
array('host' => $baseUrl,
"debug" => true)
);
But I am getting error in this line PostHog::init, the error says
"Attempted to load class PostHog" from the global namespace. Did you forget a "use" statement?"
In fact, I am already using the "use" as following "use PostHog\PostHog;", but I am still getting this error. I can confrim that the Posthog library is intall becuase I can read the classess in Poshog library from my codebase.
This is more info about my app:
I use Symfony framework 5 and the app is deployed in docker. I use PHP 7.4 and posthog/posthog-php": "2.1.1".
I checked the vendor folder and PostHog is there (see photo attached)
I implemented service call PosthogHandler where I use PostHog functions (like init, capture and etc). I am calling functions' services from controller. But the issue is that the error appear in the PosthogHandler constructor in line PostHog::init, at PostHog initialisation stage. This is my PosthogHandler service class:
<?php
declare(strict_types=1);
namespace App\Posthogs;
use PostHog\PostHog;
use App\User\User;
class PosthogHandler
{
public function __construct($env, string $key, string $baseUrl)
{
PostHog::init($key,
array('host' => $baseUrl,
"debug" => true)
);
}
public function addEvent(string $eventName, User $user){
PostHog::capture(array(
'distinctId' => $user->getId()->id(),
'event' => $eventName
));
}
}
Any help, why I am getting above error?
CodePudding user response:
The error indicates that your class file could not be autoloaded properly. You might want to check first that PostHog
is present in vendor/autoload.php
by creating a test file to check
<?php
require_once 'vendor/autoload.php';
var_dump(class_exists('Posthog\Posthog'));
If not you should try this command
composer dump-autoload
CodePudding user response:
It works!
I have three vendor folders in (1) Frontend (1) Controller (3) Services.
Before, I only installed the PostHog library in services folder where I use PostHog functions. This didn't seem working despite the posthog lib appeared in vendor folder.
What it makes work and the error disappears when I installed the posthog lib in controller folder. I don't use posthog in controller at all, I am not sure why I need to install the posthog lib in controller folder in order to work. But eventually it works!