Symfony将一些实体注入监听器

时间:2016-07-14 13:00:59

标签: php symfony

需要一些建议。 我想更新现在看到的文章。 首先,我将EM注入监听器。但解析url获取加载文章的文章ID并不适合symfony,就像我看来的那样。

services:
    app.articles.action_listener:
        class: FrontendBundle\EventListener\ArticleListener
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
        arguments: ['@doctrine.orm.entity_manager']

是否有任何选项可以让实体在控制器中发生?

/**
 * @Route("/{id}", requirements={"page": "\d+"}, name="article_view_full")
 *
 * @param Article $article
 *
 * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
 */
public function viewAction(Article $article)

更新

/**
 * Class ArticleListener
 * @package FrontendBundle\EventListener
 */
    class ArticleListener
    {
        /**
         * @type EntityManager
         */
        private $manager;

        /**
         * ArticleListener constructor.
         *
         * @param EntityManager $manager
         */
        public function __construct(EntityManager $manager)
        {
            $this->manager = $manager;
        }

        /**
         * @param $event
         */
        public function onKernelController($event)
        {

            $controller = $event->getController();

            if (!is_array($controller)) {
                return;
            }

            if ($controller[0] instanceof ArticlesController && $controller[1] == 'viewAction') {
                // THIS IS THE FULL ARTICLE VIEW. HERE I NEED TO GET CURRENT ARTICLE INSTANCE AND UPDATE VIEWS COLUMN IN DB. 
            }
        }
    }

请求任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以将服务容器解析为参数

arguments: ['@doctrine.orm.entity_manager','@service_container']

然后获取参数......

 public function __construct( $em, Container $container     ) {
    $this->em = $em;
    $this->container    = $container;
    $rq                 = $this->container->get( 'request_stack' );
    $rq                 = $rq->getCurrentRequest();
    $parameters         = explode( '/', $rq->getRequestUri() );

您还可以从事件中获取请求:

$request = $event->getRequest();