Symfony2のバンドル内に簡単なクラスを作成しました。
class MyTest {
public function myFunction() {
$logger = $this->get('logger');
$logger->err('testing out');
}
}
どうすればコンテナにアクセスできますか?
サービスコンテナを注入する必要があります。クラスは次のようになります。
use Symfony\Component\DependencyInjection\ContainerInterface;
class MyTest
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function myFunction()
{
$logger = $this->container->get('logger');
$logger->err('testing out');
}
}
次に、コントローラーまたはContainerAwareインスタンス内で:
$myinstance = new MyTest($this->container);
さらに説明が必要な場合:http ://symfony.com/doc/current/book/service_container.html
ほとんどの場合、コンテナ全体を注入することはお勧めできません。必要なサービスを個別に注入します。
namespace Vendor;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
class MyTest
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function myFunction()
{
$logger->err('testing out');
}
}
でサービスを登録しますservices.yml
:
services:
my_test:
class: Vendor\MyTest
arguments: [@logger]
@logger
サービスだけを追加してみませんか?例えば
arguments: [@logger]
コンテナを追加する場合(推奨されないもの)、を追加でき@service_container
ますservices.yml
。