laravel-container
Laravel 容器是完全独立的,即使你的项目不是基于 Laravel 框架的,依然可以使用 Laravel 的服务容器,只要通过 Composer 安装 illuminate/container 就好了。想了解更多关于容器的知识?去读源码吧!容器在底层只有一个类 IlluminateContainerContainer 读完了你就会对容器如何工作有更深的理解。
初始化composer.json
安装laravel-container
psr-4 autoload
AppApplication
helpers.PHP
index.PHP
初始化composer.json
vi composer.json
{
"name": "laravel/container",
"description": "Laravel Container.",
"keywords": ["container","laravel"],
"license": "MIT",
"type": "project",
"require": {
"PHP": "^7.0.0"
},
"autoload": {
},
"minimum-stability": "dev",
"prefer-stable": true
}
安装laravel-container
composer require illuminate/container
psr-4 autoload
vi composer.json
{
"autoload": {
"files": [
"app/Support/helpers.PHP"
],
"psr-4": {
"App\": "app/"
}
}
}
AppApplication
vi app/Application.PHP
namespace App;
use IlluminateContainerContainer;
class Application extends Container
{
public function __construct()
{
static::setInstance($this);
}
}
helpers.PHP
vi app/Support/helpers.PHP
function app($abstract = null,array $parameters = [])
{
if (is_null($abstract)) {
return IlluminateContainerContainer::getInstance();
}
return IlluminateContainerContainer::getInstance()->make($abstract,$parameters);
}
index.PHP
vi public/index.PHP
require __DIR__ . '/../vendor/autoload.PHP';
$app = new AppApplication();
$app->instance('name','Cuber');
s($app->make('name'));
s(app('name'));
s(app());