2.4. Dependency Injection

Next, let's inject Service component into Action component.

Please create the following Action class in the classes directory. You can specify a component name by @S2Component annotation. Moreover, please implement the $service property which receives the instance of Service class. By setting public accession to $service property, Service component will be injected to by the property injection function. Within the indexAction method, it can process using the injected Service component.

<?php
/**
 * @S2Component('name' => 'act')
 */
class Action{
    public $service = null;
    public function indexAction() {
        $result = $this->service->add(1, 2);
    }
}

Next, create the following Service class.

<?php
class Service {
    public function add($a, $b) {
        return $a + $b;
    }
}

Requiring of Action class and Service class is performed by the s2import function. When Action component is taken out by the get method of S2ApplicationContext, the instance of the Service class will be injected into $service property of Action instance.

<?php
require_once('S2Container.php');

s2import(dirname(__FILE__) . '/classes');
$action = s2get('act');
var_dump($action);

[Note]NOTE

This Example is located at "examples/quickstart/quickstart020.php".



© Copyright The Seasar Foundation and the others 2005-2010, all rights reserved.