Question

I have the following code (trying to simulate a factory pattern):

CoinConnectorFactory.php

public static function build($connector) {
    $connector = "CoinConnector" . ucwords($connector);
    if (class_exists($connector)) {
        return new $connector();
    } else {
        throw new InvalidConnectorType($connector);
    }
}

And the following folder structure:

/app
    /Plugin
        /CoinConnector
             /Lib
                 CoinConnectorFactory.php
                 CoinConnectorGogulski.php

So the problem is, I pass to the build method as a $connector variable this value gogulski but when get into class_exists like this:

class_exists('CoinConnectorGogulski')

Never find the class (that have the same name that the file) and always throw the exception.

Only if I add this line before check if the class exist CakePHP is able to find the class

include_once APP . 'Plugin' . DS . 'CoinConnector' . DS . 'Lib' . DS . $connector . '.php';
Was it helpful?

Solution

That is how I fix my problem at the end:

public static function build($connector) {
    $connector = "CoinConnector" . ucwords($connector);
    App::uses($connector, 'CoinConnector.Lib');
    if (class_exists($connector)) {
        return new $connector();
    } else {
        throw new InvalidConnectorType($connector);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top