25. ZendCrypt
Dependency Injection Smell: Missing dependency auto-recovery
If you have a dependency, act like you are .
publicstaticfunctiongetSymmetricPluginManager()
{
if(static::$symmetricPlugins===null){
static::setSymmetricPluginManager(newSymmetricPluginManager());
}
returnstatic::$symmetricPlugins;
}
PHP
25/44
26. ZendCrypt
Dependency Injection Smell: Hidden dependencies
If you have a dependency, make it explicit.
classSymmetricPluginManagerextendsAbstractPluginManager
{
protected$invokableClasses=array(
'mcrypt'=>'ZendCryptSymmetricMcrypt',
);
}
PHP
26/44
31. SymfonyBundleFrameworkBundle
Dependency Injection Smell: Factory methods
Don't require developers to use inheritance for replacing dependencies.
abstractclassHttpCacheextendsBaseHttpCache
{
protectedfunctioncreateEsi()
{
returnnewEsi();
}
protectedfunctioncreateStore()
{
returnnewStore($this->cacheDir?:$this->kernel->getCacheDir().'/http_cache');
}
}
PHP
31/44
32. SymfonyBundleFrameworkBundle
Dependency Injection Smell: Programming against an implementation
HttpCachehas a dependency on HttpKernelInterface...
abstractclassHttpCacheextendsBaseHttpCache
{
publicfunction__construct(HttpKernelInterface$kernel,$cacheDir=null)
{
...
}
}
PHP
interfaceHttpKernelInterface
{
publicfunctionhandle(Request$request,$type=self::MASTER_REQUEST,$catch=true);
}
PHP
32/44
33. SymfonyBundleFrameworkBundle
Dependency Injection Smell: Programming against an implementation
... but it uses of the interface methods
array('debug'=>$kernel->isDebug()), PHP
returnnewStore($this->cacheDir?:$this->kernel->getCacheDir().'/http_cache'); PHP
$this->getKernel()->boot(); PHP
33/44
38. DoctrineDBAL
Dependency Injection Smell: Dependencies prohibited
We can not override Type::__construct()since it is final.
Don't neglect other classes' needs (even if your class has everything it needs)
Type::addType('encrypted_string','EncryptedStringType'); PHP
abstractclassType
{
finalprivatefunction__construct(){}
}
PHP
38/44
40. DoctrineDBAL
Recommended refactoring
1. Split the Typeclass into an AbstractTypeand a TypeRegistry.
2. Set a type instance, instead of just a class.
$blockCipher=...;//ha,weknowhowtomakeone!
$typeRegistry=newTypeRegistry();
$encryptedStringType=newEncryptedStringType($blockCipher);
$typeRegistry->setType('encrypted_string',$encryptedStringType);
PHP
40/44
43. Keep in mind...
Be clear and open about what your dependencies are
Require only a minimum amount of dependencies
Develop with your users (other developers) in mind
·
·
·
43/44
44. Thank you
Please leave some feedback at joind.in/8447
twitter @matthiasnoback
www php-and-symfony.matthiasnoback.nl
github github.com/matthiasnoback
leanpub leanpub.com/a-year-with-symfony