PHP code example of coapsyfactor / objectfactory

1. Go to this page and download the library: Download coapsyfactor/objectfactory library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

coapsyfactor / objectfactory example snippets



interface IModel {}
class Model implements IModel {}

\ObjectFactory\Factory::registerInterfaceClass(IModel::class, Model::class);



interface IDatabase {}
class MySQL implements IDatabase
{
    public function __constructor(string $host, string $username, string $password, string $schema) {}
}

class PostgreSQL implements IDatabase
{
    public function __constructor(string $host, string $username, string $password, string $schema, string $role = null) {}
}

\ObjectFactory\Factory::registerInterfaceInstanceProvider(IDatabase::class, function (): IDatabase {
    switch (getenv('database.driver')) {
        case 'psql':
            return new PostgreSQL('localhost', 'admin', '', 'db', 'admin');
        case 'mysql':
        default:
            return new MySQL('localhost', 'root', '', 'database');
    }
});


$nonShared = \ObjectFactory\Factory::getInstance(IModel::class);
$shared1 = \ObjectFactory\Factory::getSharedInstance(IModel::class);
$shared2 = \ObjectFactory\Factory::getSharedInstance(IModel::class);

var_dump($nonShared === $shared1, $shared1 === $shared2); // false, true will be the output.