sciactive/requirephp

An implementation of dependency injection (like RequireJS) in PHP.

1.3.0 2015-02-19 00:00 UTC

This package is auto-updated.

Last update: 2024-12-07 15:43:03 UTC


README

Latest Stable Version License Total Downloads Open Issues

An implementation of dependency injection and service locator (like RequireJS) in PHP.

Installation

You can install RequirePHP with Composer or Bower.

composer require sciactive/requirephp

bower install https://github.com/sciactive/requirephp.git

Getting Started

If you don't use an autoloader, all you need to do is include the RequirePHP.php file.

require("RequirePHP.php");

Now you can start giving code that requires a module, or modules, to run. This code will not run until all the required modules (in this case, only 'test') are available.

\SciActive\RequirePHP::_(array('test'), function($test){
	$test->value = '<p>Hello, world.</p>';
});

You can define modules. This module has no dependencies, hence the empty array.

\SciActive\RequirePHP::_('test', array(), function(){
	class test {
		public $value;

		public function talk() {
			echo $this->value;
		}
	}

	// Returning a new instantiation is important if you are
	// providing a service.
	return new test();
});

You can create aliases to modules (and other aliases).

\SciActive\RequirePHP::alias('testing', 'test');

You can keep using the same instance in other code, using RequirePHP as a service locator. This function uses the alias from above.

\SciActive\RequirePHP::_(array('testing'), function($test){
	$test->talk(); // Prints '<p>Hello, world.</p>'.
});

You can also retrieve modules outside of a closure. However, if this module is not available at the time you request it, RequirePHP will throw a RequireModuleFailedException. Such is the price of not using a closure.

$test = \SciActive\RequirePHP::_('test');
$test->talk(); // Prints '<p>Hello, world.</p>'.

Service Location

The repository contains an example of using RequirePHP as a service locator.

Dependency Injection

The repository contains an example of using RequirePHP as a dependency injector.

Contacting the Developer

There are several ways to contact RequirePHP's developer with your questions, concerns, comments, bug reports, or feature requests.