coapsyfactor/objectfactory

提供相关接口对象实例的工厂

v1.0.1 2020-03-11 22:34 UTC

This package is auto-updated.

Last update: 2024-09-16 07:55:56 UTC


README

在此文档中,您可以找到此库的正确用法。

关于

此库用于轻松检索特定对象的实例,无需提供所有依赖项。

需求

  • PHP: >=7.4

概述

此库确保提供实现特定接口或属于特定类型的类的正确实例。依赖项必须是复杂类型,因为原始类型(字符串、整数、浮点数、布尔值)不能被精确地自动确定。定义特定接口的“提供者”有两种方式。

用法

第一种方法是提供接口和类本身的简单映射,为此需要调用registerInterfaceClass方法。

interface IModel {}
class Model implements IModel {}

\ObjectFactory\Factory::registerInterfaceClass(IModel::class, Model::class);
注意:仅在提供类具有复杂类型依赖项时使用此方法,提供原始类型将导致抛出异常。
注意:库通过在检测到循环依赖时抛出异常来处理循环依赖。

另一种方法是使用提供者回调函数,该函数在请求实例时被调用,为此需要调用registerInterfaceInstanceProvider。此方法通常在对象依赖于原始类型时很有用。

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

检索特定类型实例有两种方式。一种是getInstance,它始终返回请求类型的全新实例。

还有一种方法是使用getSharedInstance,它始终返回请求模型的单例实例。

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