【发布时间】:2018-11-21 05:24:29
【问题描述】:
有人可以帮我在 Symfony3.4 中自动装配吗?
我正在尝试实现以下监听器,但我不知道注入 VoteManagerInterface。这是错误,我的代码和我的配置。谢谢你的帮助:)
无法自动装配服务“AppBundle\EventListener\CommentVoteListener”:方法“__construct()”的参数“$voteManager”引用接口“FOS\CommentBundle\Model\VoteManagerInterface”,但不存在此类服务。您可能应该将此接口别名为以下现有服务之一:“fos_comment.manager.vote.default”、“fos_comment.manager.vote.acl”。
<?php
namespace AppBundle\EventListener;
use FOS\CommentBundle\Event\VotePersistEvent;
use FOS\CommentBundle\Events;
use FOS\CommentBundle\Model\VoteManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Description of CommentVoteListener
*
*/
class CommentVoteListener implements EventSubscriberInterface {
private $voteManager;
private $token_storage;
public function __construct(VoteManagerInterface $voteManager, TokenStorageInterface $token_storage) {
$this->voteManager = $voteManager;
$this->token_storage = $token_storage;
}
/**
* Assumptions:
* 1) User is logged in (caught by FOSCB acl)
* 2) VoteBlamerListener has already run which assigned the voter (this event has priority of -1)
*
* Make sure the user has not already voted, and make sure that the user is not the author.
*
* @param VotePersistEvent $event
* @return void
*/
public function onVotePrePersist(VotePersistEvent $event) {
$vote = $event->getVote();
$user = $this->token_storage->getToken()->getUser();
// make sure user is not the author
if ($vote->getComment()->getAuthor() === $user) {
$this->stopPersistence($event);
}
// make sure user hasn't already voted
$existingVote = $this->voteManager->findVoteBy(array('comment' => $vote->getComment(), 'voter' => $user));
if (null !== $existingVote && $vote->getValue() === $existingVote->getValue()) {
$this->stopPersistence($event);
}
}
protected function stopPersistence(VotePersistEvent $event) {
$event->abortPersistence();
$event->stopPropagation();
}
public static function getSubscribedEvents() {
return array(
Events::VOTE_PRE_PERSIST => array('onVotePrePersist', -1),
);
}
}
}
app.listener.vote:
class: AppBundle\EventListener\CommentVoteListener
arguments:
- "@fos_comment.manager.vote.acl"
- "@security.token_storage"
tags:
- { name: kernel.event_listener, event: fos_comment.vote.pre_persist, method: onVotePrePersist }
或
app.listener.vote:
class: AppBundle\EventListener\CommentVoteListener
arguments: ["@fos_comment.manager.vote.acl", "@security.token_storage"]
tags:
- { name: kernel.event_listener, event: fos_comment.vote.pre_persist, method: onVotePrePersist }
【问题讨论】:
-
将 app.listener.vote 替换为完全限定的类名。 autowire 的 auto 部分正在尝试自动连接您的侦听器,因为没有以该类作为键的服务退出。
-
我不太了解@Cerad。我与另一个线程预持久侦听器具有相同的结构,并且效果很好,就是这样:
app.listener.thread:class: AppBundle\EventListener\PostThreadListenerarguments:- "@security.token_storage"tags:- { name: kernel.event_listener, event: fos_comment.thread.pre_persist, method: onThreadPrePersist }
标签: symfony autowired event-listener symfony-3.4 foscommentbundle