by Kevin Schroeder | 1:31 pm

In a previous article I showed how you could pass in a fully qualified parameter name into the Dependency Injection Container (DiC) if you needed to be specific about where you need to have something injected.  There is an alternate method here that is cleaner than what I did before.  Let’s start with a Test class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Test
{
  protected $test;
 
  public function setTest($test)
  {
    $this->test = $test;
  }
 
  public function getTest()
  {
    return $this->test;
  }
}

The way I did it in the previous example was by defining the fully qualified parameter name by doing this.

1
2
3
4
5
6
7
8
9
$config = array(
  'instance' => array(
    'Test' => array( // Class name
      'parameters' => array(
        'Test::setTest:0' => 'some data';
      )
    )
  )
);

Which is fine until you you have

1
2
3
4
5
6
7
8
9
$config = array(
  'instance' => array(
    'FriggingLongNamespacedClass' => array( // Class name
      'parameters' => array(
        'FriggingLongNamespacedClass::setFriggingLongNamespacedClassMethod:0' => 'some data';
      )
    )
  )
);

It can get a little convoluted, plus I’m not entirely convinced that’s the best way of doing it.  Parameters seem to be more useful for doing constructor injection.  A better method for setters seems to be through the use of injectors.  Let’s take at an injector configuration.

1
2
3
4
5
6
7
8
9
10
11
$config = array(
  'instance' => array(
    'Test' => array( // Class name
      'injections' => array(
        'setTest' => array(
          array('test' => 'somedata')
        )
      )
    )
  )
);

Basically, rather an using the “parameter” key use “injections” and specify an array of injection methods.  Each of those methods needs an associative array of parameter names as the key with the values as the value.  Injectors seem to be much nicer and cleaner than my previous way of doing the fully qualified parameter.

Comments

No comments yet...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.