gpt4 book ai didi

Symfony2 事件监听器并获得对内核、请求和响应的访问权限?

转载 作者:行者123 更新时间:2023-12-03 15:05:41 26 4
gpt4 key购买 nike

我真的很难理解这一点,现在我只是在兜兜转转。

我已经阅读了尽可能多的手册,支付了视频教程的费用,搜索了 Google 和 YouTube,但无法使其正常工作。

我只是想设置一个在每个请求之前激活的监听器。我可以做到这一点,但我的问题是访问我需要的各种其他部分。

下面是一个例子,但我认为现在只有实际的代码才能帮助我理解这一点。

如果有人可以填写空白,我将不胜感激。这只是一个例子,但每一部分都会向我解释我需要知道什么。

在 config.yml 中:

services:
kernel.listener.request_listener:
class: Acme\Bundle\NewBundle\EventListener\RequestListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
arguments: [ '@service_container' ]

类:
namespace Acme\Bundle\NewBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
***do I need to 'use' any others here?***

class RequestListener
{

public function onKernelRequest($container) {

//reference to these: http://api.symfony.com/2.1/Symfony/Component/HttpKernel/Event/KernelEvent.html
$kernel =

//reference to the Request object
$request = $kernel->getRequest();

//reference to the Response object
$response =

//options:
// (1) continue to run usual content
// (2) stop execution and output a message
// (3) set cookie and continue to run usual content
switch( $request->query->get('option') ) {

case 1:
return
case 2:

$this->setResponse("hello, message here");

break;
case 3:
// *** not sure if this is the way to do it ***
$response->headers->setCookie(new Cookie("test", 1));
break;

}

}

}

最佳答案

您的 services.yml 几乎没有错误
为了使您的代码工作,这应该看起来像

服务.yml

services:
listener.requestresponse:
class: My\AwesomeBundle\Listener\MyListener
arguments: ['@service_container']
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

My\AwesomeBundle\Listener\MyListener.php
namespace My\AwesomeBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyListener
{
protected $container;

public function __construct(ContainerInterface $container) // this is @service_container
{
$this->container = $container;
}

public function onKernelRequest(GetResponseEvent $event)
{
$kernel = $event->getKernel();
$request = $event->getRequest();
$container = $this->container;
}

public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
$request = $event->getRequest();
$kernel = $event->getKernel();
$container = $this->container;

switch ($request->query->get('option')) {
case 2:
$response->setContent('Blah');
break;

case 3:
$response->headers->setCookie(new Cookie('test', 1));
break;
}
}
}

关于Symfony2 事件监听器并获得对内核、请求和响应的访问权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15471227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com