Factory Patterns in PHP and Python

Published by Ryan on

Factory patterns allow you to call different codebases dynamically. Layered with a common interface a factory pattern is powerful for processing similar data returned from different APIs. I’ll add context later, maybe a factory pattern tutorial. But for now just saving the crux of implementations I’ve done in PHP and Python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
* PHP factory class, passing a dependency container
* for app specific code and infrastructure
*/

class APIFactory
{
    public static $providers = [];
    public static $dc;
    public static function connect($dc, $provider)
    {
        // For now, check a hardcoded variable
        if(!in_array($provider, self::$providers)) {
            throw new \Exception('Provider not supported: '.$provider, 500);
        }
        // Assumes we have codebase in the following namespace
        $className = __NAMESPACE__.'\\APIProviders\\'.$provider.'\\'.$provider;
        $config = getConfigMethod($provider);
        return new $className($dc, $config);
    }
}

/*
* Usage. Will attempt to look for an construct file/class:
* APIProviders\\providername\\providername() and run an authenticate()
* method from that class
*/

$provider = APIFactory::connect($dc, "providername");
$provider->authenticate();

In this python implementation, we assume that each api codebase exists in a module.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import os, sys, string, importlib

'''
Python factory class
'''

class APIFactory:
    providers = []

    @staticmethod
    def connect(provider):
        // For now, check a hardcoded variable
        if provider not in providers:
            raise Exception('Provider not supported: '+str(provider));

        // Assumes we have codebase in the following location
        sys.path.append(os.path.dirname(os.path.abspath(__file__))+'/APIProviders/')
        module = importlib.import_module(provider)
        config = getConfigMethod(provider)
        return getattr(module, provider)(config);

'''
Usage. Will attempt to look for a module:
APIProviders/providername and run an authenticate()
method from that module
'''

provider = APIFactory.connect("providername");
provide.authenticate();

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *