FunkitonInjectorBundle provides means for injecting services to controllers by using simple annotations.
-
Add this bundle to your project as Git submodules:
$ git submodule add git://github.com/Funkiton/InjectorBundle.git vendor/bundles/Funkiton/InjectorBundle
-
Add the Funkiton namespace to your autoloader:
// app/autoload.php $loader->registerNamespaces(array( 'Funkiton' => DIR.'/../vendor/bundles', // your other namespaces ));
-
Add this bundle to your application's kernel:
// application/ApplicationKernel.php public function registerBundles() { return array( // ... new Funkiton\InjectorBundle\FunkitonInjectorBundle(), // ... ); }
-
Configure the
funkiton_injectorservice in your config:funktion_injector: ~
Add needed (depends on which type of injection is needed) use stataments to your controller php file:
// ...
use Funkiton\InjectorBundle\Annotation\Inject;
use Funkiton\InjectorBundle\Annotation\TryInject;
// ...
And annotations to your controller class docblock:
/**
* @Inject("security.context", name="security");
* @Inject("request::getSession", name="session");
* @TryInject("user");
*/
class MyController
{
// ...
Optionally define the visibility level of properties as usual:
* ...
*/
class MyController
{
private $user;
protected $session;
}
Now you should be able to access injected services by $this->service_name.
@Inject- injects service, doesn't check for exceptions that might happen@TryInject- injects service, if DI-related exception is thrown injects null instead.
Annotations take service name as their default argument. Additionally service_name::method
form is accepted. In this case not service is injected but the return value of specified method.
It's worth to mention that if no name is given in annotation the service name is used as property name replacing all consecutive non-alphanumeric characters with underscore:
security.context::getToken -> security_context_getToken
So use name argument to specify more friendly name for injected property (or see next chapter):
@Inject("security.context::getToken", name="token")
You can configure service aliases to use in annotations.
For example add this to your config:
# app/config/config.yml
funkiton_injector:
definitions:
security: security.context
user: funkiton_injector.helper::getUser
session: request::getSession
em: doctrine::getEntityManager