Skip to content

Instantly share code, notes, and snippets.

@avalanche123
Created January 17, 2011 18:39
Show Gist options
  • Save avalanche123/783229 to your computer and use it in GitHub Desktop.
Save avalanche123/783229 to your computer and use it in GitHub Desktop.
<?php
interface TemplatingAware
{
function setTemplating(EngineInterface $engine);
}
interface RouterAware
{
function setRouter(RouterInterface $router);
}
class AbstractController implements TemplatingAware, RouterAware
{
protected $engine;
protected $router;
public function setTemplating(EngineInterface $engine)
{
$this->engine = $engine;
}
public function setRouter(RouterInterface $router)
{
$this->router = $router;
}
}
class SomeController extends AbstractController
{
///some code
}
class SomeOtherController extends AbstractController
{
///some code
}
<interface class="TemplatingAware">
<call method="setTemplating">
<argument type="service" id="templating" />
</call>
</interface>
<interface class="RouterAware">
<call method="setRouter">
<argument type="service" id="router" />
</call>
</interface>
<service id="some.controller" class="SomeController" />
<service id="some.other.controller" class="SomeOtherController" />
@avalanche123
Copy link
Author

now SomeController and SomeOtherController will have $engine and $router properties populated with correct services

@johnkary
Copy link

Shouldn't public function setRouter(Router $router) type hint on the interface? public function setRouter(RouterInterface $router) ?

@avalanche123
Copy link
Author

oh, yeah, let me fix that, thanks

@Koc
Copy link

Koc commented Jan 18, 2011

Имхо не самый удачный пример. Почему бы не сделать просто interface ContainerAware и

class AbstractController implements ContainerAware
{
  protected function getTemplating()
  {
    return $this->container->get('templating');
  }
}

@avalanche123
Copy link
Author

You're free to use whatever you want. This is to show how you could achieve less configuration for controllers as services using interface injection.
Keep in mind that no matter how many controllers you have registered in DIC, as long as they extend this base AbstractController class, they will all get templating and routing without a single line of extra configuration.
What you're showing is just a different way of getting services in controller, and is not relevant to this example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment