PHP code example of wp-forge / container

1. Go to this page and download the library: Download wp-forge/container library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wp-forge / container example snippets




use WP_Forge\Container\Container;

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

// Set a value
$container->set('email', '[email protected]');

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

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

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



use WP_Forge\Container\Container;

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

// Set a value
$container['email'] = '[email protected]';

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

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

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



use WP_Forge\Container\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 instance.
$factory = $container->get( 'session' );

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



use WP_Forge\Container\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 instance.
$service = $container->get( 'session' );

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



use WP_Forge\Container\Container;

$container = new Container( [
	'first_name'  => 'John',
	'last_name'   => 'Doe',
] );

$container->set( 'full_name', $container->computed( function ( Container $container ) {
	return implode( ' ', array_filter( [
		$container->has( 'first_name' ) ? $container->get( 'first_name' ) : '',
		$container->has( 'last_name' ) ? $container->get( 'last_name' ) : '',
	] ) );
} ) );

$full_name = $container->get( 'full_name' );



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

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

    return $instance;
} );