单独使用Laravel容器 laravel-container

laravel-container

Laravel 容器是完全独立的,即使你的项目不是基于 Laravel 框架的,依然可以使用 Laravel 的服务容器,只要通过 Composer 安装 illuminate/container 就好了。想了解更多关于容器的知识?去读源码吧!容器在底层只有一个类 Illuminate\Container\Container 读完了你就会对容器如何工作有更深的理解。

初始化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/"
        }
    }
}

App\Application

vi app/Application.php

namespace App;

use Illuminate\Container\Container;

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 Illuminate\Container\Container::getInstance();
    }

    return Illuminate\Container\Container::getInstance()->make($abstract, $parameters);
}

index.php

vi public/index.php

require __DIR__ . '/../vendor/autoload.php';

$app = new App\Application();

$app->instance('name', 'Cuber');
s($app->make('name'));
s(app('name'));
s(app());
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页