ServiceLocatorTest.php 2.39 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yiiunit\framework\di;

use yii\base\Object;
11
use yii\di\ServiceLocator;
Qiang Xue committed
12 13 14 15
use yiiunit\TestCase;

class Creator
{
16
    public static function create()
Qiang Xue committed
17
    {
18
        return new TestClass;
Qiang Xue committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
    }
}

class TestClass extends Object
{
    public $prop1 = 1;
    public $prop2;
}

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ServiceLocatorTest extends TestCase
{
    public function testCallable()
    {
        // anonymous function
37
        $container = new ServiceLocator;
Qiang Xue committed
38
        $className = TestClass::className();
39 40
        $container->set($className, function () {
            return new TestClass([
Qiang Xue committed
41 42 43 44 45 46 47 48 49 50
                'prop1' => 100,
                'prop2' => 200,
            ]);
        });
        $object = $container->get($className);
        $this->assertTrue($object instanceof $className);
        $this->assertEquals(100, $object->prop1);
        $this->assertEquals(200, $object->prop2);

        // static method
51
        $container = new ServiceLocator;
Qiang Xue committed
52 53 54 55 56 57 58 59 60 61 62 63
        $className = TestClass::className();
        $container->set($className, [__NAMESPACE__ . "\\Creator", 'create']);
        $object = $container->get($className);
        $this->assertTrue($object instanceof $className);
        $this->assertEquals(1, $object->prop1);
        $this->assertNull($object->prop2);
    }

    public function testObject()
    {
        $object = new TestClass;
        $className = TestClass::className();
64
        $container = new ServiceLocator;
Qiang Xue committed
65 66 67 68 69 70 71
        $container->set($className, $object);
        $this->assertTrue($container->get($className) === $object);
    }

    public function testShared()
    {
        // with configuration: shared
72
        $container = new ServiceLocator;
Qiang Xue committed
73 74
        $className = TestClass::className();
        $container->set($className, [
75
            'class' => $className,
Qiang Xue committed
76 77 78 79 80 81 82 83 84 85 86 87 88
            'prop1' => 10,
            'prop2' => 20,
        ]);
        $object = $container->get($className);
        $this->assertEquals(10, $object->prop1);
        $this->assertEquals(20, $object->prop2);
        $this->assertTrue($object instanceof $className);
        // check shared
        $object2 = $container->get($className);
        $this->assertTrue($object2 instanceof $className);
        $this->assertTrue($object === $object2);
    }
}