Example #1
0
 public function test_can_resolve_out_of_the_ioc_container()
 {
     IoC::bind('foo', function () {
         return new Foo();
     });
     $this->assertInstanceOf('Foo', IoC::make('foo'));
 }
 public function purchaseDiscountedProduct($product, $discountPercentage)
 {
     $origPrice = $product->getPrice();
     $newPrice = $origPrice - $discountPercentage / 100 * $origPrice;
     $discountedProduct = IoC::make('Product', [$product->getName(), $newPrice]);
     $this->logger->log("Applying discount to " . $product->getName());
     $this->purchase($discountedProduct);
 }
    {
        $this->service = $service;
    }
    public function getReview(APIRequest $request, APIResponse $response)
    {
        $vars->review = $this->getPerformanceReviewService()->buildPerformanceReview($this->reviewId);
        $vars->questions = $this->getPerformanceReviewService()->buildReviewQuestions($this->reviewId);
        $vars->answers = $this->getPerformanceReviewService()->buildReviewAnswers($this->reviewId);
        echo json_encode($this->vars);
    }
    public function updateReview(APIRequest $request, APIResponse $response)
    {
        $reviewId = $request->get('id');
        try {
            //The API could use a different Request object, as long as it implements the right
            //interface.
            $reviewAnswers = new ReviewAnswersRequest($reviewId, $request->post('questions'));
        } catch (InvalidArgumentException $exception) {
            //invalid data posted.
            $response->errorCode(400);
            $response->errorMessage('You did it wrong!');
            return true;
        }
        $this->getPerformanceReviewService()->answerReviewQuestions($reviewAnswers);
        $response->successCode(200);
        return true;
    }
}
IoC::bind('DB', $db);
$api = IoC::make(ReviewServiceApi::class);
$api->getReview($request, $response);
//$foo = new Foo(new Bar(new Bim()));
//$foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething
class IoC
{
    protected static $registry = [];
    public static function bind($name, callable $resolver)
    {
        static::$registry[$name] = $resolver;
    }
    public static function make($name)
    {
        if (isset(static::$registry[$name])) {
            $resolver = static::$registry[$name];
            return $resolver();
        }
        throw new Exception('Alias does not exist in the IoC registry.');
    }
}
IoC::bind('bim', function () {
    return new Bim();
});
IoC::bind('bar', function () {
    return new Bar(IoC::make('bim'));
});
IoC::bind('foo', function () {
    return new Foo(IoC::make('bar'));
});
// 从容器中取得Foo
$foo = IoC::make('foo');
$foo->doSomething();
// Bim::doSomething|Bar::doSomething|Foo::doSomething