PHP Classes

PHP Object Factory: Create objects of given types defined by name

Recommend this page to a friend!
  Info   View files Example   View files View files (4)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not yet rated by the usersTotal: 99 All time: 9,784 This week: 148Up
Version License PHP version Categories
objectfactory 1.0.0BSD License7Data types, Language, PHP 7
Description 

Author

This package can be used to create objects of given types defined by interface.

It provides a means to register an interface that will be associated to a class that will be used to create the object when the getInstance or getShared functions of the factory are called passing the identification of the interface.

The package can also register an interface provider by associating to a callback function, so when the getInstance or getSharedInstance functions of the factory is called, it will invoke a given callback function that takes as parameter a string with a name that can be used by the callback function to determine what is the class of the object that will be created.

Innovation Award
PHP Programming Innovation award nominee
March 2020
Number 4
Sometimes applications need to implement a certain functionality in a dynamic way.

This means that the way that functionality will be implemented is not determined initially when the current PHP script starts, as it depends on factors that will be evaluated later during the execution of the script.

This package provides a solution to implement that possibility by providing means for registering interfaces dynamically to implement the desired functionality.

Manuel Lemos
Picture of Aleksandar Zivanovic
  Performance   Level  
Name: Aleksandar Zivanovic <contact>
Classes: 16 packages by
Country: Serbia Serbia
Age: 30
All time rank: 16237 in Serbia Serbia
Week rank: 314 Up2 in Serbia Serbia Up
Innovation award
Innovation award
Nominee: 4x

Example

<?php

require_once __DIR__ . '/vendor/autoload.php';

interface
IModel {}
abstract class
BaseModel implements IModel{}

interface
IUserModel extends IModel {}
class
UserModel extends BaseModel implements IUserModel {}

interface
IAccountModel extends IModel {
    public function
getUser(): IUserModel;
}
class
AccountModel extends BaseModel implements IAccountModel {
    private
IUserModel $user;

    public function
__construct(IUserModel $user)
    {
       
$this->user = $user;
    }

    public function
getUser(): IUserModel
   
{
        return
$this->user;
    }
}

interface
ICharacterAccount extends IAccountModel {}
class
CharacterAccountModel extends AccountModel implements ICharacterAccount {
    private
IAccountModel $userAccount;

    public function
__construct(IAccountModel $userAccount)
    {
       
parent::__construct($userAccount->getUser());

       
$this->userAccount = $userAccount;
    }
}

\
ObjectFactory\Factory::registerInterfaceClass(IUserModel::class, UserModel::class);
\
ObjectFactory\Factory::registerInterfaceInstanceProvider(IAccountModel::class, function (): IAccountModel {
    return \
ObjectFactory\Factory::getInstance(AccountModel::class);
});
\
ObjectFactory\Factory::registerInterfaceClass(ICharacterAccount::class, CharacterAccountModel::class);

$nonShared = \ObjectFactory\Factory::getInstance(AccountModel::class);
$sharedA = \ObjectFactory\Factory::getSharedInstance(AccountModel::class);
$sharedB = \ObjectFactory\Factory::getSharedInstance(AccountModel::class);
\
ObjectFactory\Factory::getInstance(CharacterAccountModel::class);

var_dump($nonShared === $sharedA, $sharedA === $sharedB);


Details

Object Factory

In this document you can find proper usage of this library.

About

This library is used to easily retrieve instance of certain object without the need to provide all of its dependencies.

Requirements

  • PHP: >=7.4

Overview

This library ensure to provide proper instance of object implementing certain interface, or being certain type of a class. Dependencies are required to be complex type as primitive ones (string, int, float, bool) cannot be exactly auto determined. There are two ways of defining "provider" for certain interface.

Usage

First approach is providing simple map between interface and class itself, to do so we need to call `registerInterfaceClass` method.


interface IModel {}
class Model implements IModel {}

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

Note: Use this only when providing class has complex typed dependencies, providing class with primitive types will cause exception to be thrown.
Note: Library handle circular dependencies.

Another approach is using provider callback- function that is called when instance is requested, to achieve this we need to call `registerInterfaceInstanceProvider`. This approach is usually useful when object depends on primitive types.


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');
    }
});

There are two ways to retrieve instance of certain type. One is `getInstance` which always returns new instance of requested type.

And there is also another way by using `getSharedInstance` which always return signleton instance of requested model.


$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.


  Files folder image Files  
File Role Description
Files folder imagesrc (1 file)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file example.php Example Class source
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  src  
File Role Description
  Plain text file Factory.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:99
This week:0
All time:9,784
This week:148Up