gpt4 book ai didi

php - Zend Framework 函数不是 Controller 中的操作

转载 作者:可可西里 更新时间:2023-10-31 23:16:04 26 4
gpt4 key购买 nike

在 Controller 中创建一个不是 Action 的函数是不好的做法吗?

例子:下面Controller中的createCookie函数

protected $translator;
protected $cookie;

public function __construct($translator, $cookie)
{
$this->translator = $translator;
$this->cookie = $cookie;
}

public function changeLanguageAction()
{
$language = $this->params()->fromRoute('lang', 'en');
$this->createCookie('xuage', $language, '/');
$this->getResponse()->getHeaders()->addHeader($this->cookie);
$this->redirect()->toRoute('home');
}

public function createCookie($name, $value, $path)
{
$this->cookie->setName($name);
$this->cookie->setValue($value);
$this->cookie->setPath($path);
}

最佳答案

我建议创建一个 CookieService,并在此服务中使用公共(public)方法 createCookie。然后,您可以将此服务注入(inject)到您的 Controller 类中,并在您的操作中调用此方法,而不会用额外的 cookie 相关逻辑污染您的 Controller 类。

protected $translator;
protected $cookieService;

public function __construct($translator, CookieService $cookie)
{
$this->translator = $translator;
$this->cookieService = $cookieService;
}

public function changeLanguageAction()
{
$language = $this->params()->fromRoute('lang', 'en');
$this->cookieService->createCookie('xuage', $language, '/');
$this->redirect()->toRoute('home');
}

将 cookie 添加到响应中也可以在此服务中完成。所以这一行将在您的 CookieService 中解决:

$this->getResponse()->getHeaders()->addHeader($this->cookie);

关于php - Zend Framework 函数不是 Controller 中的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42003582/

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