Technical Docs

Search Documentation

Function: tribe_singleton

Registers a class as a singleton.

Located at src/Tribe/Container.php (Line: 83)

Description

Each call to obtain an instance of this class made using the

tribe( $slug )

function will return the same instance; the instances are built just in time (if not passing an object instance or callback function) and on the first request. The container will call the class

__construct

method on the class (if not passing an object or a callback function) and will try to automagically resolve dependencies.

Example use:

 tribe_singleton( 'tec.admin.class', 'Tribe__Admin__Class' );  // some code later...  // class is built here  tribe( 'tec.admin.class' )->doSomething();

Need the class built immediately? Build it and register it:

 tribe_singleton( 'tec.admin.class', new Tribe__Admin__Class() );  // some code later...  tribe( 'tec.admin.class' )->doSomething();

Need a very custom way to build the class? Register a callback:

 tribe_singleton( 'tec.admin.class', array( Tribe__Admin__Class__Factory, 'make' ) );  // some code later...  tribe( 'tec.admin.class' )->doSomething();

Or register the methods that should be called on the object after its construction:

 tribe_singleton( 'tec.admin.class', 'Tribe__Admin__Class', array( 'hook', 'register' ) );  // some code later...  // the `hook` and `register` methods will be called on the built instance.  tribe( 'tec.admin.class' )->doSomething();

The class will be built only once (if passing the class name or a callback function), stored and the same instance will be returned from that moment on.

Parameters summary

(string) $slug The human-readable and catchy name of the class.
(string|object|callable) $class The full class name or an instance of the class or a callback that will return the instance of the class.
(array) $after_build_methods An array of methods that should be called on the built object after the <code>__construct</code> method; the methods will be called only once after the singleton instance construction.

Return value summary

(void)

Examples

void tribe_singleton ( string $slug, string|object|callable $class, array $after_build_methods = null )