How to Install and Use ThinkPHP’s Container for Dependency Injection

This guide shows how to install the think-container package via Composer, explains its PSR‑11‑compatible features, and provides step‑by‑step PHP code examples for retrieving, binding, invoking, and using Facade shortcuts with the ThinkPHP container.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
How to Install and Use ThinkPHP’s Container for Dependency Injection

Installation

composer require topthink/think-container

Features

Supports PSR‑11 standard

Supports dependency injection

Supports Facade pattern

Supports container object binding

Supports closure binding

Supports interface binding

Container Usage

// Get container instance
$container = \think\Container::getInstance();

// Bind a class, closure, instance, or interface implementation
$container->bind('cache', '\app\common\Cache');

// Check if an object exists
$container->has('cache');

// Retrieve the unique instance
$container->get('cache');

// Retrieve or automatically instantiate if missing
$container->make('cache');

// Delete an object from the container
$container->delete('cache');

// Invoke a callable with dependency injection
$container->invoke($callable, $vars);

// Instantiate a class with dependency injection
$container->invokeClass($class, $vars);

// Static method to pull an instance (auto‑instantiates if absent)
\think\Container::pull('cache');

Object‑style operations

// Get container instance
$container = \think\Container::getInstance();

// Bind using property syntax
$container->cache = '\app\common\Cache';

// Check existence
isset($container->cache);

// Retrieve the unique instance
$container->cache;

// Delete the binding
unset($container->cache);

Facade

Define a Facade class (e.g., app\facade\App) that extends think\Facade. The Facade maps static calls to the underlying dynamic class ( \think\App).

<?php
namespace think;
class App {
    public function name() {
        return 'app';
    }
}
<?php
namespace app\facade;
use think\Facade;
class App extends Facade {
    /**
     * Get the class name that the Facade represents
     * @access protected
     * @return string
     */
    protected static function getFacadeClass() {
        return '\\think\\App';
    }
}

After defining the Facade, you can call the dynamic method statically:

use app\facade\App;

echo App::name(); // outputs "app"
Facadedependency-injection
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.