Search code examples
phpsymfonysymfony4

dynamic class loading - Attempted to load class _CLASS_ from namespace _NAMESPACE_


So i try to load a class inside a service in Symfony4. It doesn't matter if i load it as classname or as App\to\class\name\classname.
It generates the same error.

Other posts said you need to add the whole fully qualified classname..
This doesn't work. Am I missing something? Code below:

<?php
// src/Service/AdwordsService.php
namespace App\Service;

use App\Service\AdTypes\ExpendedTextAdTypes as ExpendedTextAdTypes;

class AdwordsService{ 
    ...
    public function getAdsModel($ad) //<-- for example "EXPANDED_TEXT_AD"
    {
        $type = explode('_',strtolower($ad->getType()));
        $modelName = array_map('ucfirst', $type);
        $modelName = implode('',$modelName).'Types';
        // will load ExpandedTextAdTypes
        return new $modelName($ad);
    }
    ...
}

Class that it tries to load:

<?php
// src/Service/AdTypes/ExpendedTextAdTypes.php
namespace App\Service\AdTypes;

class ExpendedTextAdTypes
{

    private $adData;

    public function __construct($ad)
    {
        $this->adData = $ad;
    }
}

Solution

  • The ultimate problem(s) was a simple typo: EXPANDED_TEXT_AD vs EXPENDED_TEXT_AD along with the need to use a fully qualified class name:

    // No need for any use statements
    // use App\Service\AdTypes\ExpendedTextAdTypes as ExpendedTextAdTypes;
    
    public function getAdsModel($ad) //<-- for example "EXPENDED_TEXT_AD"
    {
        $type = explode('_',strtolower($ad));
        $modelName = array_map('ucfirst', $type);
        $modelName = implode('',$modelName).'Types';
        $modelName = 'App\\Service\\AdTypes\\' . $modelName; // Add this
        return new $modelName($ad);
    }
    

    As a rule, typo questions are considered to be off-topic. But this question actually has two issues as well as pointing out that the use statement is not needed. So I guess it can qualify as an answer.

    The question's title is also misleading. I clicked on the question because I had never seen CLASS in an error message. It would have been better to have posted the actual error message thus possible making it easier to detect the typo.

    And finally, a bit of unsolicited advice. This sort of transformation from EXPENDED_TEXT_AD to ExpendedTextAdTypes can be difficult to maintain and definitely locks you in to a class naming scheme. Why not just use ExpendedTextAd instead of EXPENDED_TEXT_AD? Symfony does this sort of thing all the time.