我正在處理一個EntityRepository類,並且需要將一些數據轉儲到我的日誌文件中。我不能使用dump(),因爲這不會構建頁面;它只是要返回一些JSON。最終。在Symfony中獲取記錄器不在控制器中
通常情況下,在控制,我會使用:
$logger = $this->getLogger();
但我不是一個控制器。
Thx尋求幫助。
更新:這是用於法醫記錄。我只是將它用於調試目的。它將在之後被刪除。
我正在處理一個EntityRepository類,並且需要將一些數據轉儲到我的日誌文件中。我不能使用dump(),因爲這不會構建頁面;它只是要返回一些JSON。最終。在Symfony中獲取記錄器不在控制器中
通常情況下,在控制,我會使用:
$logger = $this->getLogger();
但我不是一個控制器。
Thx尋求幫助。
更新:這是用於法醫記錄。我只是將它用於調試目的。它將在之後被刪除。
我看了一下。我的第一個預感是「好吧,如果你可以定義EntityRepositories作爲服務,那麼這將使這很容易,因爲你可以然後只是注入記錄器」
但是,如何將注入器注入到該教義正在創建的存儲庫?事實證明,你可以specify your own repository factory
我將假設所有需要的是實現Doctrine\ORM\Repository\RepositoryFactory
接口,但你可能想要子類Doctrine\ORM\Repository\DefaultRepositoryFactory
。
您還需要創建自己的,可以容納記錄器的基礎存儲庫類。讓我們從這裏開始
的src /的appbundle /教義/ EntityRepository.php
<?php
namespace AppBundle\Doctrine;
use Doctrine\ORM\EntityRepository;
use Psr\Log\LoggerInterface;
class LoggerAwareEntityRepository extends EntityRepository
{
protected $logger;
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
現在,工廠
的src /的appbundle /教義/ LoggerAwareRepositoryFactory.php
<?php
namespace AppBundle\Doctrine;
use Doctrine\ORM\Repository\DefaultRepositoryFactory;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use AppBundle\Doctrine\LoggerAwareEntityRepository;
class LoggerAwareRepositoryFactory extends DefaultRepositoryFactory
{
protected $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
protected function createRepository(EntityManagerInterface $entityManager, $entityName)
{
$repository = parent::createRepository($entityManager, $entityName);
if ($repository instanceof LoggerAwareEntityRepository) {
$repository->setLogger($this->logger);
}
return $repository;
}
}
現在的配置膠水,使其一切工作
應用程序/配置/ services.yml
services:
logger_aware_repository_factory:
class: AppBundle\Doctrine\LoggerAwareRepositoryFactory
arguments: ['@logger']
應用程序/配置/ config.yml
doctrine:
orm:
entity_managers:
default:
repository_factory: "@logger_aware_repository_factory"
最後,對於實際執行
的src /的appbundle /Entity/SomeCustomRepository.php
<?php
namespace AppBundle\Entity;
use AppBundle\Doctrine\LoggerAwareEntityRepository;
class SomeCustomRepository extends LoggerAwareEntityRepository
{
public function findSomethingCustom()
{
// Log something
$this->logger->log('message');
}
}
完全披露:這是未經測試的代碼 - 可能有錯誤!
從Doctrine 2.4開始,您也可以直接設置存儲庫工廠。 $ config-> setRepositoryFactory(new \ AppBundle \ Doctrine \ LoggerAwareRepositoryFactory($ logger)); – Julian
所有這一切只是一個記錄器。而在其他框架中,您只需在應用程序中暴露一個。 Symfony已經做出了一些奇怪的選擇。 – eggmatters
根據您想要記錄的內容,最簡潔的解決方案是創建一個doctrine或doctrine實體監聽器,可能在後期加載。在記錄器中注入記錄器。 一旦你決定不需要它,只需刪除監聽器。
引用:您不應該將容器傳遞到存儲庫,就像您永遠不應該讓實體處理重邏輯一樣。存儲庫只有一個目的 - 從數據庫中檢索數據。沒有更多(閱讀:http://docs.doctrine-project.org/en/2.0.x/reference/working-with-objects.html)。 –
日誌記錄始終是一項元任務。他們從不爲應用程序的服務工作,他們爲開發人員服務。在破解之前,你必須知道規則,除非你願意實現類似AOP的東西,那麼你必須稍微打破SRP才能添加日誌記錄。 –