kecik/dic

Kecik 框架的依赖注入容器 (DIC) 库

1.0.3 2015-04-17 17:28 UTC

This package is not auto-updated.

Last update: 2024-09-28 18:26:29 UTC


README

此库是一个支持解决依赖注入容器问题的库,因此库是一个对象、控制器,它可以是模型,或者库只会被加载一次,以避免浪费。

安装

编辑 composer.json 文件

{
	"require": {
		"kecik/dic": "dev-master"
	}
}

运行命令

composer install

使用示例

<?php
require "vendor/autoload.php";
$config = array (
	'libraries' => array (
		'DIC' => array (
			'enable' => TRUE
		)
	),
);

$app = new Kecik\Kecik($config);

class Test1 {
	public function __construct() {
		echo "Hello is Test1 <br />";
	}
}

class Test2 {
	public function __construct(Test1 $test) {
		echo "Hello is Test2 <br />";
	}

	public function index() {
		echo 'Is Index';
	}
}

$app->container['Test1'] = function($c) {
	return new Test1();
};

$app->container['Test2'] = function($c) {
	return new Test2($c['Test1']);
};

$app->container['Test3'] = $app->container->factory(function($c) {
	return new Test2($c['Test1']);
});

$app->get('/', function() use ($app){
	$app->container['Test1'];
	$app->container['Test2']->index();
});

$app->run();
?>

或者对于控制器

WelcomeController

文件: welcome.php

<?php
namespace Controller;

use Kecik\Controller;

class Welcome extends Controller {
	public function __construct() {
		echo 'Hello is Welcome Controller';
	}
}

HelloController

文件: hello.php

<?php
namespace Controller;

use Kecik\Controller;

class Hello extends Controller {
	public function __construct(Welcome $welcome) {
		echo 'Hello is Hello Controller';
	}
	public function say($name) {
		echo "Hello, $name";
	}
}

索引

文件: index.php

<?php
require "vendor/autoload.php";

$config = array (
	'libraries' => array (
		'DIC' => array (
			'enable' => TRUE
		)
	),
);

$app = new Kecik\Kecik($config);

$app->container['WelcomeController'] = function($c) {
	return new Controller\Welcome();
};

$app->container['HelloController'] = function($c) {
	return new Controller\Hello($c['WelcomeController']);
};

$app->get('/', function() use ($app){
	$app->container['WelcomeController'];
});

$app->get('hell/:name', function($name) use ($app) {
	$app->container['HelloController']->say($name);
});
$app->run();
?>