wpscholar/container

该包已被弃用且不再维护。未建议替代包。

轻量级PHP 5.4+ 兼容的依赖注入容器。

1.0 2019-03-01 22:08 UTC

This package is auto-updated.

Last update: 2020-08-30 01:57:12 UTC


README

轻量级PHP 5.4+ 兼容的依赖注入容器。

用法

项目基本操作。

<?php

// Create a new instance
$container = new wpscholar\Container();

// Set a value
$container->set('email', 'webmaster@site.com');

// Check if a value exists
$exists = $container->has('email');

// Get a value
$value = $container->get('email');

// Delete a value
$container->delete('email');

使用数组语法的基本操作。

<?php

// Create a new instance
$container = new wpscholar\Container();

// Set a value
$container['email'] = 'webmaster@site.com';

// Check if a value exists
$exists = isset( $container['email'];

// Get a value
$value = $container['email'];

// Delete a value
unset( $container['email'] );

注册一个工厂。每次获取工厂时都会返回一个新的类实例。

<?php

use wpscholar\Container;

// Create a new instance
$container = new Container();

// Add a factory
$container->set( 'session', $container->factory( function( Container $c ) {
    return new Session( $c->get('session_id') );
} ) );

// Get a factory
$factory = $container->get( 'session' );

// Check if an item is a factory
$isFactory = $container->isFactory( $factory );

注册一个服务。每次获取服务时都会返回相同的类实例。

<?php

use wpscholar\Container;

// Create a new instance
$container = new Container();

// Add a service
$container->set( 'session', $container->service( function( Container $c ) {
    return new Session( $c->get('session_id') );
} ) );

// Get a service
$service = $container->get( 'session' );

// Check if an item is a service
$isService = $container->isService( $service );

扩展之前已注册的工厂或服务。

<?php

use wpscholar\Closure;

$container->extend( 'session', function( $instance, Closure $c ) {

    $instance->setShoppingCart( $c->get('shopping_cart') );

    return $instance;
} );