-
Notifications
You must be signed in to change notification settings - Fork 5
BasicUsage
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.moo.com/xsd/bounce-beans-1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:php="http://www.moo.com/xsd/bounce-php-1.0"
xsi:schemaLocation="
http://www.moo.com/xsd/bounce-beans-1.0 file:///home/steves/moo/lib/moocommon-infra/src/resources/bounce-beans-1.0.xsd
http://www.moo.com/xsd/bounce-php-1.0 file:///home/steves/moo/lib/moocommon-infra/src/resources/bounce-php-1.0.xsd
">
<bean name="logger" class="\MyApp\FileLogger">
<property name="logLevel">
<php:constant>\MyApp\Logger::LEVEL_DEBUG</php:constant>
</property>
<property name="logfile" value="/var/log/myapp.log" />
</bean>
<bean name="ApiClient" class="\MyApp\Api">
<property name="client">
<bean class="\MyApp\OAuthSigningClient">
<property name="logger" ref="logger" />
<property name="key" value="asdasdasdasdasdsdsa" />
<property name="secret" value="badsfasdsadasdadssadsad" />
</bean>
</property>
<property name="logger" ref="logger" />
</bean>
</beans>$xmlContext = new \MooDev\Bounce\Context\XmlApplicationContext($xmlFile);
$client = $xmlContext->get("ApiClient");
// $client is now a working \MyApp\Api instance.So, what's happened here is that you've defined a bean called ApiClient. This will be an instance of \MyApp\Api. When it gets instantiated (when you ask for it first time) Bounce will set the named properties on instance. In this case the client property, which itself is an instance of \MyApp\OAuthSigningClient (again bounce will instantiate this), and logger which references another named bean.
You'll notice that logger is referenced twice by other beans: by ApiClient and by its nested (and unnamed) OAuthSigningClient. This will cause one instance of the logger bean to be created, and that single instance will be set wherever it's referenced.
Yes, this can be done in many other ways. Most obviously, these things could be passed in as constructor params to each of these classes. That does indeed work, but produces a lot of boilerplate, and makes life hard when dealing with top-level shared instances (e.g. logger in this case.) You can work around that by using singletons, but then testing becomes annoying.
Using a dependency injection framework such as Bounce is a reasonably convenient way to solve this set of problems.