sonrisa/factory-component

此包已被废弃且不再维护。未建议替代包。

sonrisa框架的工厂组件。支持PHP5.3及以上版本。

1.0.0 2013-08-12 18:02 UTC

This package is not auto-updated.

Last update: 2018-01-07 08:46:44 UTC


README

1. 描述

Factory组件允许通过PHP的ReflectionClass创建类。

使用Factory组件的目的是让开发者有权决定在整个执行线程中是否创建类的单个实例,或者创建多个类的实例。

Factory组件可以实例化普通和Singleton类,如果需要,允许用户将参数(作为数组)传递给类的__construct或getInstance方法。

2. 方法

  • getInstance()
  • create($classPath,$args=array(),$unique=false)
  • get($classPath)
  • remove($classPath)
  • removeAll()

3. 使用

Factory组件的使用非常简单

3.1 - 在整个执行线程中为每个类创建单个实例

    $factory = \NilPortugues\Component\Factory\ClassFactory::getInstance();

    //One instance of these classes will be created.
    //This is determined by the "true" value at the end of the create method.

    //We'll be passing an argument to the DateTime class. 
    //Arguments should be passed in the same order defined in the class.
    $dateTime = $factory->create("\\DateTime",array('2013-08-08'),true);

    //We'll be passing no values to the StdClass constructor
    $stdClass = $factory->create("\\StdClass",array(),true);

3.2 - 在整个执行线程中创建多个类实例

    $factory = \NilPortugues\Component\Factory\ClassFactory::getInstance();

    //Create a class instance using the Factory Class.
    $dateTime = $factory->create("\\DateTime",array('2013-08-08'));

    //Which is actually the same as doing...
    $instance = new \DateTime('2013-08-08');

3.3 - 获取现有类实例

    $factory = \NilPortugues\Component\Factory\ClassFactory::getInstance();
    $dateTime = $factory->create("\\DateTime",array('2013-08-08'),true);

    //Call the code below in another function or class
    $dateTime = $factory->get('\\DateTime');

    var_dump($dateTime);                // Outputs: object(DateTime) ...
    echo $dateTime->format('Y-m-d');    // Outputs 2013-08-08

3.4 - 从Factory中删除一个或所有类

请不要尝试删除Factory中未注册的类,否则会抛出FactoryException异常。


    $factory = \NilPortugues\Component\Factory\ClassFactory::getInstance();

    //throws FactoryException
    $factory->remove('\\DateTime');

    //this will throw a FactoryException too as the DateTime object hasn't been stored to make it unique.
    $dateTime = $factory->create("\\DateTime",array('2013-08-08'));
    $factory->remove('\\DateTime');

    //remove DateTime
    $dateTime = $factory->create("\\DateTime",array('2013-08-08'),true);
    $factory->remove('\\DateTime');

    //removeAll will not throw a FactoryException if empty.
    $factory->removeAll();

4. 已完全测试。

测试已使用PHPUnit和Travis-CI进行。所有过滤器都已测试,确保从PHP 5.3至PHP 5.5的兼容性。