Skip to content

Instantly share code, notes, and snippets.

@shochdoerfer
Created January 6, 2012 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shochdoerfer/1569872 to your computer and use it in GitHub Desktop.
Save shochdoerfer/1569872 to your computer and use it in GitHub Desktop.
ZF2 DI sample
// describe dependency
$dep = new \Zend\Di\Definition\Builder\PhpClass();
$dep->setName('my\TalkRepository');
// describe class
$class = new \Zend\Di\Definition\Builder\PhpClass();
$class->setName('my\TalkService');
// add injection method
$im = new \Zend\Di\Definition\Builder\InjectionMethod();
$im->setName('__construct');
$im->addParameter('repo', 'my\TalkRepository');
$class->addInjectionMethod($im);
// configure builder
$builder = new \Zend\Di\Definition\BuilderDefinition();
$builder->addClass($dep);
$builder->addClass($class);
// add to Di
$defList = new \Zend\Di\DefinitionList($builder);
$di = new \Zend\Di\Di($defList);
$service = $di->get('my\TalkService');
var_dump($service);
<?php
namespace my;
interface GenericRepository {
public function readTalks();
}
class TalkRepository implements GenericRepository {
public function readTalks() {
}
}
class TalkService {
public function __construct(TalkRepository $repo) {
}
public function getTalks() {
}
}
The configuration above leads to the following exception:
PHP Fatal error: Uncaught exception 'Zend\Di\Exception\ClassNotFoundException' with message 'Class y could not be located in provided definition.' in /tmp/library/Zend/Di/Di.php:163
Stack trace:
#0 /tmp/library/Zend/Di/Di.php(129): Zend\Di\Di->newInstance('y', Array)
#1 /tmp/library/Zend/Di/Di.php(578): Zend\Di\Di->get('y', Array)
#2 /tmp/library/Zend/Di/Di.php(306): Zend\Di\Di->resolveMethodParameters('my\TalkService', '__construct', Array, true, NULL, true)
#3 /tmp/library/Zend/Di/Di.php(172): Zend\Di\Di->createInstanceViaConstructor('my\TalkService', Array, NULL)
#4 /tmp/library/Zend/Di/Di.php(129): Zend\Di\Di->newInstance('my\TalkService', Array)
#5 /tmp/htdocs/index.php(34): Zend\Di\Di->get('my\TalkService')
#6 {main}
thrown in /tmp/library/Zend/Di/Di.php on line 163
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment